gpt4 book ai didi

c# - 动态初始化 iset

转载 作者:太空宇宙 更新时间:2023-11-03 10:33:51 28 4
gpt4 key购买 nike

在构建类时,我想用 HashSet 动态初始化所有 ISet,

下面是我如何用 List 实现 IList

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.. 在这种情况下如何实现它??

最佳答案

PropertyInfo.SetValue 需要 object,因此您不必转换 constructorInfo.Invoke(null) 的结果:

var listInstance = constructorInfo.Invoke(null);
property.SetValue(this, listInstance);

关于c# - 动态初始化 iset<t>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28688916/

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