vendredi 7 juillet 2017

Using Reflection to test Generic Objects [duplicate]

This question already has an answer here:

I have a C# class which looks like this:

public class SpproRepository<T> : IRepository where T : ISpproEntity
{
  // Code here
}

and I have a context class which looks like this

public class SeymourSpContext : SpproBaseContext
{
    public virtual SpproRepository<Properties> Properties { get; set; }
}

Now I am trying to instantiate all my Properties which are of type SpproRepository (where I dont define T, except that it implements ISpproEntity.

My problem is simply that I can not figure out how to check if property is of type SpproRepository

Here is one of my many attempts:

    public SpproBaseContext(string siteUrl)
    {
        var type = this.GetType();      
        foreach (var property in type.GetProperties())     //Itterate Through all properties, if they are type SpproRepository instantiate        
        {                
            if (property.PropertyType.GetInterfaces().Where(a=> a.GetType() == typeof(IRepository)).Any())   //I Implemented IRepository as a test, this didnt work. Ideally it would be something like Property.PropertyType is SpproRepository<>; but this doesnt either
            {
                 //code below here works as it should
                var listType = typeof(SpproRepository<>);
                var genericArgs = property.PropertyType.GetGenericArguments();
                var concreteType = listType.MakeGenericType(genericArgs);
                var listName = genericArgs[0].Name;
                var newRepo = Activator.CreateInstance(concreteType, listName);
                property.SetValue(this, newRepo);
            }
        }

    }





Aucun commentaire:

Enregistrer un commentaire