我有一个特殊的情况,在其中一个反射器中,我可以得到需要重新充气的不同类型的容器(例如对其进行克隆)。当引入新型容器时,这种情况开始发生(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:方法只能在Type.IsGenericParameter为true的Type上调用。
我的猜测是我需要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的答案了。
那你应该看看他的答案。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句