假设我有一个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()是我正在寻找的功能的占位符。
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.
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>.
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.
最满意答案
使用Type.GetGenericTypeDefinition()方法。 它将返回一个类型的泛型定义,例如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包含你想要实现的内容。
Use Type.GetGenericTypeDefinition() method. It will return a generic definition of a type, e.g. List<> from List<Whatever>. And then you can create a type with a generic arguments you want with Type.MakeGenericType(params Type[] typeArguments) method:
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.
更多推荐
发布评论