【问题标题】:dynamically intitialize iset<t>动态初始化 iset<t>
【发布时间】: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


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2015-04-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-10
    • 2012-06-26
    • 1970-01-01
    • 2012-02-10
    • 1970-01-01
    相关资源
    最近更新 更多