【发布时间】:2015-02-25 00:37:19
【问题描述】:
在构造类时,我想用HashSet动态初始化所有的ISet,
下面是我如何为 IList with List 实现它
var properties = GetType()
.GetProperties()
.Where(x => x.PropertyType.IsGenericType &&
x.PropertyType.GetGenericTypeDefinition() == typeof(IList<>))
.ToList();
foreach (var property in properties)
{
// get T type of ISet
if (property.PropertyType.GetGenericArguments().Length > 1) continue;
var listElemType = property.PropertyType.GetGenericArguments()[0];
if (listElemType == null) continue;
// create hashedset
var constructorInfo = typeof(List<>)
.MakeGenericType(listElemType)
.GetConstructor(Type.EmptyTypes);
//construct object
if (constructorInfo == null) continue;
var listInstance = (IList)constructorInfo.Invoke(null);
property.SetValue(this, listInstance);
}
但是如果我对 ISet 尝试同样的事情,它就不起作用:(
var properties = GetType()
.GetProperties()
.Where(x => x.PropertyType.IsGenericType &&
x.PropertyType.GetGenericTypeDefinition() == typeof(ISet<>))
.ToList();
foreach (var property in properties)
{
// get T type of ISet
if (property.PropertyType.GetGenericArguments().Length > 1) continue;
var listElemType = property.PropertyType.GetGenericArguments()[0];
if (listElemType == null) continue;
// create hashedset
var constructorInfo = typeof(HashSet<>)
.MakeGenericType(listElemType)
.GetConstructor(Type.EmptyTypes);
//construct object
if (constructorInfo == null) continue;
//============== HERE IS THE PROBLEM ============
// var listInstance = (ISet)constructorInfo.Invoke(null);
// property.SetValue(this, listInstance);
}
没有像 IList 一样的 ISet.. 在这种情况下如何实现它??
【问题讨论】:
-
有什么问题?
-
你为什么要投
listInstance为什么不直接留下object? -
@leppie 他的问题是没有非通用的
ISet接口,所以他不知道将listInstance转换为什么。 -
@ScottChamberlain 是的,将其作为对象完成工作.. 无需投射...感谢您的快速回答
-
@ScottChamberlain:好地方:D
标签: c# generics reflection