首页 新闻 会员 周边

利用反射实现深拷贝,为什么拷贝不了字典类型

0
悬赏园豆:20 [已解决问题] 解决于 2019-11-26 19:09

void DeepCopyObj <T> (T oSource , T nSource)
{
PropertyInfo[] props = typeof(T).GetPropertise();
foreach(PropertyInfo p in p.where(o => o.DeclaringType == typeof(T)))
{
if (p.CanWrite)
p.SetValue(nSource , p.GetValue(oSource , null ) , null);
}
}

代码如上,简单的利用反射拷贝对象,当传递进去的对象的属性中包含List、Dictionary时,List类型都可以正常拷贝,为什么Dictionary类型的拷贝不了,输出的nSouce中,字典类型的为null(源oSource中是有数据的)

Finder~的主页 Finder~ | 初学一级 | 园豆:11
提问于:2019-11-21 14:31
< >
分享
最佳答案
0

自己调试解决了。并非以上深拷贝代码问题,问题出在要拷贝的对象,如果其属性声明采用非简化的set、get声明方式,必须写全。否则调System.Reflection.SetValue就是赋值不了的

Finder~ | 初学一级 |园豆:11 | 2019-11-26 19:07
其他回答(1)
0

class Program
{
static void Main(string[] args)
{
Person person = new Person();
person.Nmae = "name";
Dictionary<int, string> Dic = new Dictionary<int, string>();
Dic.Add(1, "1");
Dic.Add(2, "2");
person.Dic = Dic;
Person person1 = new Person();
DeepCopyObj<Person>(person, person1);
}

    static void DeepCopyObj<T>(T oSource, T nSource)
    {
        PropertyInfo[] props = nSource.GetType().GetProperties();
        foreach (PropertyInfo p in props)
        {
            if (p.CanWrite)
                p.SetValue(nSource, p.GetValue(oSource, null), null);
        }
    }
}

public class Person
{
    public string Nmae { get; set; }

    public Dictionary<int,string> Dic { get; set; }
}

Dictionary是可以的,DeepCopyObj 是按照你的改的

收获园豆:20
猝不及防 | 园豆:2781 (老鸟四级) | 2019-11-21 16:59

多谢你的关注,问题已解决,属性本身声明的问题。

支持(0) 反对(0) Finder~ | 园豆:11 (初学一级) | 2019-11-26 19:08
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册