首页 新闻 会员 周边

C#如何反射创建动态泛型对象?

0
悬赏园豆:60 [已关闭问题] 关闭于 2020-02-22 17:09

比如我在类A里面有一个属性List<B>,我怎么样才能在反射读取类A的属性的时候,判断List<B>这个字段如果是泛型类型,就实例化List<B>,然后创建多个B,填充到List<B>,

我现在可以实例化多个B,但是无法填充到List<B>中去。

大致代码如图,最后setValue的时候,提示类型无法转换,

反射代码写的少,不知道是不是哪儿姿势不对,熬夜爆肝到半夜,实在是无法解决

问题补充:
public class A
    {
        public string Name { get; set; }

        public List<B> Url { get; set; }

    }

    public class B
    {
        /// <summary>
        /// Age
        /// </summary>
        public string Name { get; set; }
    }

反射代码如下

 public T Parse<T>(string html) where T : class, new() //T 为A
        {
            var t = new T();
            var properties = t.GetType().GetProperties();
            if (properties == null)
            {
                return t;
            }
            foreach (var item in properties)
            {
                if (item.PropertyType.IsGenericType)
                {
                    var aa = typeof(List<>);
                    var list = aa.MakeGenericType(t.GetType());
                    var testlist = Activator.CreateInstance(list);
                    var a = item.PropertyType.GetGenericArguments().FirstOrDefault();
                    var obj = new List<object>();
                    for (int i = 0; i < 10; i++)
                    {
                        var qc = Activator.CreateInstance(a);
                        foreach (var test in qc.GetType().GetProperties())
                        {
                            test.SetValue(qc, "*******");
                        }
                        obj.Add(qc);
                       
                    }
                    item.SetValue(t, obj);  //这一句报错了了
                }
            }
            return t;
        }
        
快乐海盗的主页 快乐海盗 | 初学一级 | 园豆:37
提问于:2020-02-22 04:51

建议把上面截图中的代码文本贴出来

dudu 4年前

最好能提供重现问题的代码片段

dudu 4年前

@dudu: 您好,已经贴了

天府三街第一帅 4年前
< >
分享
所有回答(1)
1

没想到睡了一觉起来几分钟搞定了。。。直接动态创建类型,不要用object和dynamic作为泛型参数去传递,直接就可以了!!

快乐海盗 | 园豆:37 (初学一级) | 2020-02-22 17:09

祝贺!欢迎贴一下解决方法。

支持(0) 反对(0) dudu | 园豆:31003 (高人七级) | 2020-02-22 19:32
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册