反射获取列表<>从List< T>(容器类型从通用容器类型)

本文关键字:类型 获取 列表 List 反射 | 更新日期: 2023-09-27 18:16:59

我有一个特殊的情况,在一个反射器,我可以得到不同类型的容器,我需要重新膨胀(如克隆)。当新型容器(ObservableCollection<T>)被引入时,这种情况开始发生

在克隆机制中,我发现如下:

if (property.PropertyType.FullName.Contains(ReflectorResources.ListName) || property.PropertyType.FullName.Contains("ConcurrentBag"))
{
    var listElementType = property.PropertyType.GenericTypeArguments[0];
    var newList = (property.PropertyType.FullName.Contains(ReflectorResources.IncidentListName))
         ? Activator.CreateInstance(typeof(Definitions.Session.Products.Motor.IncidentList<>).MakeGenericType(listElementType))
         : property.PropertyType.FullName.Contains("ConcurrentBag") ? Activator.CreateInstance(typeof(ConcurrentBag<>).MakeGenericType(listElementType)) : Activator.CreateInstance(typeof(List<>).MakeGenericType(listElementType));    
    var oneItem = Activator.CreateInstance(listElementType);
}

所以我试着把它重写成:

if (new[] { ".Collections." }.Any(o => property.PropertyType.FullName.Contains(o)))
{
    var listElementType = property.PropertyType.GenericTypeArguments[0];
    var listType = property.PropertyType;
    var constructedListType = listType.MakeGenericType(listElementType);
    var newList = Activator.CreateInstance(constructedListType);
    var oneItem = Activator.CreateInstance(listElementType);
}

但是它在行中出现了:var constructedListType = listType.MakeGenericType(listElementType); with error

系统。InvalidOperationException:方法只能在Type的类型上被调用。IsGenericParameter为true

我的猜测是,我需要从List<Something>提取List<>类型…

如何从通用容器类型获得容器类型?

反射获取列表<>从List< T>(容器类型从通用容器类型)

而不是:

var listElementType = property.PropertyType.GenericTypeArguments[0];
var listType = property.PropertyType;
var constructedListType = listType.MakeGenericType(listElementType);

试试这个:

Type listElementType = property.PropertyType.GenericTypeArguments[0];
Type constructedListType;
if (! property.PropertyType.IsGenericTypeDefinition)
    constructedListType = property.PropertyType;
else
{
    // Depending on where your property comes from
    // This should not work in the case the property type is List<T>
    // How listElementType should allow you to instantiate your type ?
    var listType = property.PropertyType.GetGenericTypeDefinition();
    constructedListType = listType.MakeGenericType(listElementType);
}

我还说你应该看看GetGenericTypeDefinition()方法,但在我写完这篇文章之前,已经有了AakashM的答案。
那你应该看看他的回答

我将引用这个答案,它可能回答了您关于反射和泛型的任何问题:

若要在运行时从构造类型获取未绑定类型,您可以使用Type.GetGenericTypeDefinition方法

Type listOfInt = typeof(List<int>);
Type list = listOfInt.GetGenericTypeDefinition(); // == typeof(List<>)