在C#中访问非泛型类型

Sjo*_*888 3 c# generics

假设我有一个类型的实体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];
Run Code Online (Sandbox Code Playgroud)

我知道我可以这样做:

Type myListType = typeof(List<>).MakeGenericType(listItemType );
Run Code Online (Sandbox Code Playgroud)

我不能这样做:

Type myListType = myList.GetType().MakeGenericType(listItemType );
Run Code Online (Sandbox Code Playgroud)

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

Type myListType = myList.GetType().GotNonGenericType().MakeGenericType(listItemType );
Run Code Online (Sandbox Code Playgroud)

哪里GotNonGenericType()是我正在寻找的功能的占位符.

lor*_*ond 6

使用Type.GetGenericTypeDefinition()方法.它将返回一个类型的泛型定义,例如List<>来自List<Whatever>.然后你可以使用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>)
Run Code Online (Sandbox Code Playgroud)

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