C# - 在泛型方法中使用运行时定义的类型作为参数
这就是我想要做的:
PropertyInfo[] propertyInfos = GetProperties(typeofEntity);
Type t = propertyInfos[0].GetType();
IList<t.GetType()> magicalList;
让我们说 t 恰好是 Int32 类型,然后我希望列表是这样的,
IList<Int32>
这不起作用,因为它与
IList<Type>
我不想写一个 相同数十次强制转换来手动查找类型。
有什么想法吗? 谢谢
编辑--------------
我这样做是因为我想传递一个对象而不是 NHibernate 查询,并自动创建与对象属性值相对应的条件。
例如:
Person{
public string Name
public Phone Phone
}
Phone{
public int Number
}
我希望能够创建一个拥有电话的人,并使用 DetachedFor<> 将其传递到 nhibernate 查询中。然后,我想自动为 Person 的“复杂”属性(例如 Phone.Number)创建条件。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您只能在编译时使用已知类型的泛型。
在您的代码中,表达式
magicalList[0]
没有编译时类型。您可以使用非泛型
IList
或通过反射完成所有操作。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:
System.Type.MakeGenericType 方法有助于创建传递参数的泛型类型。在你的情况下,你有主要类型:
There is the method System.Type.MakeGenericType wich help to create generic type passing the arguments. In your case you have the main type :