繁体   English   中英

在C#中访问非泛型类型

[英]Access non-generic type in C#

假设我有一个IList<MyClass>类型的实体,我希望将其映射到IList<MyMappedClass>类型的列表,同时保持相同的底层集合类型。

我的意思是,如果实例恰好是List<MyClass>类型,它应该映射到List<MyMappedClass>ObservableCollection<MyClass>映射到ObservableCollection<MyMappedClass>

到目前为止我所做的是我可以找到这样的列表的泛型类型:

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

我知道我可以这样做:

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

我不能这样做:

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

因为它已经是通用的。 我要找的是以下内容:

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

其中GotNonGenericType()是我正在寻找的功能的占位符。

使用Type.GetGenericTypeDefinition()方法。 它会返回一个类型的通用定义,如List<>List<Whatever> 然后,您可以使用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>)

变量newType包含您尝试实现的内容。

暂无
暂无

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

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