C# - 在通用方法中使用运行时定义的类型作为参数

时间:2011-11-03 13:16:58

标签: c# reflection types

这就是我想要做的事情:

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

让我们说t碰巧是Int32类型,然后我希望列表是

IList<Int32>

这不起作用,因为它与执行

相同
IList<Type>

我不想写十几个演员来手动找到Type。

任何想法? 感谢

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

我这样做是因为我想要传递一个没有NHibernate查询的对象,并自动创建对应于对象属性值的标准。

例如:

Person{
public string Name
public Phone Phone 
}

Phone{
public int Number
}

我希望能够使用手机创建一个人,并使用DetachedFor&lt;&gt;在nhibernate查询中传递它。然后我想自动为Person的'复杂'属性的属性创建标准,例如Phone.Number。

3 个答案:

答案 0 :(得分:4)

您只能在编译时使用已知类型的泛型 在您的代码中,表达式magicalList[0]将没有编译时类型。

您可以使用非通用IList或使用反射执行所有操作。

答案 1 :(得分:3)

尝试:

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

答案 2 :(得分:1)

方法System.Type.MakeGenericType有助于创建传递参数的泛型类型。在您的情况下,您有主要类型:

var oGenericType = typeof (IList<>);
var oSpecificType = oGenericType.MakeGenericType(typeof(int));
相关问题