简体   繁体   English

在C#中访问非泛型类型

[英]Access non-generic type in C#

Let's say I have an entity of type IList<MyClass> that I want to map to a list of type IList<MyMappedClass> while keeping the same underlying collection type. 假设我有一个IList<MyClass>类型的实体,我希望将其映射到IList<MyMappedClass>类型的列表,同时保持相同的底层集合类型。

By this I mean if the instance happens to be of type List<MyClass> it should be mapped to List<MyMappedClass> and ObservableCollection<MyClass> to ObservableCollection<MyMappedClass> . 我的意思是,如果实例恰好是List<MyClass>类型,它应该映射到List<MyMappedClass>ObservableCollection<MyClass>映射到ObservableCollection<MyMappedClass>

What I did so far is I can find the generic type of the list like this: 到目前为止我所做的是我可以找到这样的列表的泛型类型:

Type listType = myList.GetType(); //myList type: List<T> or ObservableCollection<T>
Type listItemType = listType.GetGenericArguments()[0];

I know that I can do this: 我知道我可以这样做:

Type myListType = typeof(List<>).MakeGenericType(listItemType );

I cannot do that: 我不能这样做:

Type myListType = myList.GetType().MakeGenericType(listItemType );

Because it is already generic. 因为它已经是通用的。 What I am looking for is the following: 我要找的是以下内容:

Type myListType = myList.GetType().GotNonGenericType().MakeGenericType(listItemType );

where GotNonGenericType() is a placeholder for the functionality I am looking for. 其中GotNonGenericType()是我正在寻找的功能的占位符。

Use Type.GetGenericTypeDefinition() method. 使用Type.GetGenericTypeDefinition()方法。 It will return a generic definition of a type, eg List<> from List<Whatever> . 它会返回一个类型的通用定义,如List<>List<Whatever> And then you can create a type with a generic arguments you want with Type.MakeGenericType(params Type[] typeArguments) method: 然后,您可以使用Type.MakeGenericType(params Type[] typeArguments)方法创建一个具有所需泛型参数的Type.MakeGenericType(params Type[] typeArguments)

var list    = new List<int>();
var type    = myList.GetType();                        // ~ typeof(List<int>)
var generic = type.GetGenericTypeDefinition();         // ~ typeof(List<>)
var newType = generic.MakeGenericType(typeof(string)); // ~ typeof(List<string>)

Variable newType contains what you trying to achieve. 变量newType包含您尝试实现的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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