gpt4 book ai didi

c# - .NET/C# 中是否内置了用于在对象之间复制值的内容?

转载 作者:可可西里 更新时间:2023-11-01 09:09:07 26 4
gpt4 key购买 nike

假设您有 2 个这样的类:

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);

}
}

关于c# - .NET/C# 中是否内置了用于在对象之间复制值的内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8976422/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com