gpt4 book ai didi

c# - Reflection Get List<> from List(来自通用容器类型的容器类型)

转载 作者:太空宇宙 更新时间:2023-11-03 23:07:56 25 4
gpt4 key购买 nike

我有一个特殊的情况,在其中一个反射器中我可以得到不同类型的容器,我需要重新充气(比如克隆)。这种情况在引入新型容器时开始发生 (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);有错误

System.InvalidOperationException : Method may only be called on a Type for which Type.IsGenericParameter is true.

我的猜测是我需要提取 List<>List<Something> 输入...

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

最佳答案

取而代之的是:

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 的答案。
那你应该看看他的回答。

关于c# - Reflection Get List<> from List<T>(来自通用容器类型的容器类型),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40503504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com