动态初始化list <t> </t>

时间:2015-02-24 05:43:25

标签: c# generics reflection

关于构造类,我想用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 ..在这种情况下如何实现它?

1 个答案:

答案 0 :(得分:2)

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

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