假设你有两个类:
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); } }