简体   繁体   中英

C# - Use runtime-defined type as parameter in generic method

This is what i'm trying to do:

PropertyInfo[] propertyInfos = GetProperties(typeofEntity);
Type t = propertyInfos[0].GetType();
IList<t.GetType()> magicalList;

Let us say that t happens to be of type Int32, i then want the list to be

IList<Int32>

This doesn't work, as it's just the same as doing

IList<Type>

I don't want to write a dozen casts to manually find the Type.

Any Ideas? Thanks

EDIT---------------

I'm doing this because i wanto to pass an object no an NHibernate query, and automatically create the criterias corresponding to the values of the object's properties.

Ex:

Person{
public string Name
public Phone Phone 
}

Phone{
public int Number
}

I want to be able to create a person with a phone, and pass it in an nhibernate query, using DetachedFor<>. I then want to automatically create criterias for the properties of 'complex' properties of Person, such as Phone.Number.

You can only use generics with a known type at compile-time.
In your code, the expression magicalList[0] would have no compile-time type.

You can either use a non-generic IList or do everything with reflection.

Try:

var genericType = typeof (List<>).MakeGenericType(t.GetType());
var magicalList = Activator.CreateInstance(genericType);

There is the method System.Type.MakeGenericType wich help to create generic type passing the arguments. In your case you have the main type :

var oGenericType = typeof (IList<>);
var oSpecificType = oGenericType.MakeGenericType(typeof(int));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM