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

发布于 2024-12-13 11:51:12 字数 693 浏览 4 评论 0原文

这就是我想要做的:

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

星星的轨迹 2024-12-20 11:51:12

您只能在编译时使用已知类型的泛型。
在您的代码中,表达式 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.

残龙傲雪 2024-12-20 11:51:12

尝试:

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

Try:

var genericType = typeof (List<>).MakeGenericType(t.GetType());
var magicalList = Activator.CreateInstance(genericType);
此刻的回忆 2024-12-20 11:51:12

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

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

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));
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文