关于构造类,我想使用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/

10-09 09:22