[英]Clean way to Compare / Copy between Similar Classes
We have two classes that have the exact same public accessors (and many of them) but are from different areas in the object hierarchy; 我们有两个类,它们具有完全相同的公共访问器(很多访问器),但是它们来自对象层次结构的不同区域。 we have a need to copy and compare between these two objects. 我们需要在这两个对象之间进行复制和比较。 We could manually write a copy constructor and a comparison operator which compares the values of the same-named accessors, but it seems as though there's got to be a better way to do this using reflection and LINQ. 我们可以手动编写一个复制构造函数和一个比较运算符,用于比较同名访问器的值,但是似乎必须有一种使用反射和LINQ的更好的方法。
Example: we have class ClassA which has 70 accessors; 示例:我们有ClassA类,它有70个访问器; we also have class ClassB which has 70 accessors, which are defined to be the same name and type as ClassA's accessors. 我们也有ClassB类,该类具有70个访问器,这些访问器的名称和类型与ClassA的访问器相同。
public class ClassA
{
int OneInt {get; set;}
int TwoInt {get; set;}
...
string OneString {get; set;}
string AnotherString {get; set;}
}
public class ClassB
{
int OneInt {get; set;}
int TwoInt {get; set;}
...
string OneString {get; set}
string AnotherString {get; set;}
}
What I'd like is a simple way of using reflection to discover all of the public accessors of ClassA, and use those names to set the values of the respective accessor on ClassB to the value of the accessor on ClassA. 我想要的是一种简单的方法,该方法使用反射来发现ClassA的所有公共访问器,并使用这些名称将ClassB上的各个访问器的值设置为ClassA上的访问器的值。 Roughly, in psuedocode: 大致来说,在psuedocode中:
foreach (string accName in ClassA.Accessors[])
BInstance.Accessors[accName].Value = AInstance.Accessors[accName].Value;
And, of course, the same thing could be used for testing equality between the two classes. 而且,当然,同一件事可用于测试两个类之间的相等性。 My knowledge of C# reflection and LINQ is not good enough to know how to get this done, but I'd swear it's something relatively simple. 我对C#反射和LINQ的了解不足以知道如何完成此工作,但是我发誓这是相对简单的事情。
How about using AutoMapper : 如何使用AutoMapper :
Mapper.CreateMap<ClassA, ClassB>();
and then: 接着:
ClassA classA = ...
ClassB classB = Mapper.Map<ClassA, ClassB>(classA);
It's basically an implementation of your pseudo-code. 它基本上是伪代码的实现。
your rough pseudocode is somewhat accurate. 您的粗略伪代码有些准确。 Let me clean it up a little: 让我整理一下:
foreach (var propertyA in typeof(ClassA).GetProperties())
{
var propertyB = typeof(ClassB).GetProperty(propertyA.Name);
var valueA = propertyA.GetValue(objectA, null);
propertyB.SetValue(objectB, valueA, null);
}
Obviously, this doesn't do error checking, and stuff like that, but it should do the job. 显然,这不会执行错误检查和类似的操作,但是应该可以完成工作。
You could do it in Linq, but I don't think it would be cleaner. 您可以在Linq中做到这一点,但我认为这不会更干净。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.