加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

.NET / C#中有什么内容可以复制对象之间的值吗?

发布时间:2020-12-15 17:44:08 所属栏目:百科 来源:网络整理
导读:假设你有两个类: public class ClassA { public int X { get; set; } public int Y { get; set; } public int Other { get; set; }}public class ClassB { public int X { get; set; } public int Y { get; set; } public int Nope { get; set; }} 现在想象
假设你有两个类:
public class ClassA {
    public int X { get; set; }
    public int Y { get; set; }
    public int Other { get; set; }
}

public class ClassB {
    public int X { get; set; }
    public int Y { get; set; }
    public int Nope { get; set; }
}

现在想象你有一个每个类的实例,你想要将值从a复制到b.有没有像MemberwiseClone那样会复制属性名称匹配的值(当然是容错的 – 一个有一个get,另一个是set等)?

var a = new ClassA(); var b = new classB();
a.CopyTo(b); // ??

像JavaScript这样的语言很容易.

我猜测答案是否定的,但也许有一个简单的选择.我已经写了一个反思库来做到这一点,但是如果内置到较低级别的C#/ .NET可能会更有效率(为什么要重新发明轮子).

解决方法

在对象对象映射的框架中没有任何东西,但是有一个非常受欢迎的库是这样做的: AutoMapper.

AutoMapper is a simple little library built to solve a deceptively
complex problem – getting rid of code that mapped one object to
another. This type of code is rather dreary and boring to write,so
why not invent a tool to do it for us?

顺便说一句,只是为了学习,这里是一个简单的方法,你可以实现你想要的.我还没有彻底测试它,而且它与AutoMapper一样强大/灵活/性能无处不在,但希望有一些东西可以摆脱一般的想法:

public void CopyTo(this object source,object target)
{
    // Argument-checking here...

    // Collect compatible properties and source values
    var tuples = from sourceProperty in source.GetType().GetProperties()
                 join targetProperty in target.GetType().GetProperties() 
                                     on sourceProperty.Name 
                                     equals targetProperty.Name

                 // Exclude indexers
                 where !sourceProperty.GetIndexParameters().Any()
                    && !targetProperty.GetIndexParameters().Any()

                 // Must be able to read from source and write to target.
                 where sourceProperty.CanRead && targetProperty.CanWrite

                 // Property types must be compatible.
                 where targetProperty.PropertyType
                                     .IsAssignableFrom(sourceProperty.PropertyType)

                 select new
                 {
                     Value = sourceProperty.GetValue(source,null),Property = targetProperty
                 };

    // Copy values over to target.
    foreach (var valuePropertyTuple in tuples)
    {
        valuePropertyTuple.Property
                          .SetValue(target,valuePropertyTuple.Value,null);

    }
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读