在结构之间复制属性 [英] Copy properties between structs
问题描述
有没有办法比较两个不同结构的两个实例,如果有完全相同名称的属性,是否将它们从一个实例复制到另一个实例?
Is there a way to compare two instances of two different structs and if there are properties with the exact same name, have them copied from one instance to the other?
以两个结构体为例:
struct typeA
{
public byte ID;
public byte distance;
public byte time;
}
struct typeB
{
public byte distance;
public byte length;
}
然后创建变量
typeA A;
typeB B;
接下来分配一些值
A.ID = 101;
A.distance = 12;
A.time = 5;
现在我想将变量 A 与 B 进行比较,如果有任何具有相同名称的属性(在这种情况下,两个结构都存在距离"),将它们复制到另一个变量.我不想用
Now I want to compare variable A with B and if there are any properties with the same name (in this case 'distance' exist for both struct) copy them to the other variable. I don't want to use
B.distance = A.distance
因为我不会总是知道属性的名称.
as I won't always know the names of the properties.
有人有什么想法吗?只听说过 Reflection,可以看看吗?
Does anybody have any ideas? Have only heard of Reflection, is that something to have a look at?
推荐答案
我建议您为此使用映射工具.例如.AutoMapper(可从 NuGet 获得)
I suggest you to use mapping tool for this. E.g. AutoMapper (avalable from NuGet)
Mapper.CreateMap<typeA, typeB>();
typeA A = new typeA { ID = 101, distance = 12, time = 5 };
typeB B = new typeB { length = 42 };
// ...
B = Mapper.Map(A, B);
使用默认映射 AutoMapper 将映射具有相同名称的属性.
With default mapping AutoMapper will map properties which have same names.
您应该将映射结果分配回 B
变量,因为结构体是值类型并且它们按值传递.因此,对 B
传递副本的更改不会影响原始 B
变量.上面代码的结果是带有值的变量 B
:
You should assign result of mapping back to B
variable, because structs are value types and they passed by value. So, changes to passed copy of B
will not affect original B
variable. Result of code above is variable B
with values:
{
distance: 12,
length: 42
}
这篇关于在结构之间复制属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!