.NET:是否有一个类可以将一个类的属性复制到另一个类

发布于 2024-10-01 12:03:04 字数 476 浏览 2 评论 0原文

我编写了一个函数,将一个类的属性复制到另一个类,以便复制一个对象。

比如

MyObject myObject = myOtherObject.MyCustomCopy(myObject)

myObject 和 myOtherObject 属于同一类型。我基本上是通过做这件事来做到

myObject.prop1 = myOtherObject.prop1
myObject.prop2 = myOtherObject.prop2
myObject.prop3 = myOtherObject.prop3
return myObject

这一点的,我很确定过去我使用了一个 .NET 对象,它通过反射自动执行了此操作,我猜,但不记得了......或者我想象这样的方法存在?

是的,我知道自动映射器,但我确信(现在不太确定)有一个 .NET 对象可以完成这项工作。也许不是!

I wrote a function that copies the properties of one class to another so make a copy of an object.

So something like

MyObject myObject = myOtherObject.MyCustomCopy(myObject)

where myObject and myOtherObject are of the same type. I do it by bascually doing

myObject.prop1 = myOtherObject.prop1
myObject.prop2 = myOtherObject.prop2
myObject.prop3 = myOtherObject.prop3
return myObject

I am pretty sure in the past I used a .NET object that automaticaly did this, by reflection I guess, but can't remember it ... or an I imagining that such a method exists?

Yes I'm aware of auto mapper but i was sure (not so much now) that there is a .NET object that does the job. Maybe not!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

葬﹪忆之殇 2024-10-08 12:03:04

您可以查看AutoMapper

You may take a look at AutoMapper.

怀念你的温柔 2024-10-08 12:03:04
 public static class ext
{
    public static void CopyAllTo<T>(this T source, T target)
    {
        var type = typeof(T);
        foreach (var sourceProperty in type.GetProperties())
        {
            var targetProperty = type.GetProperty(sourceProperty.Name);
            targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
        }
        foreach (var sourceField in type.GetFields())
        {
            var targetField = type.GetField(sourceField.Name);
            targetField.SetValue(target, sourceField.GetValue(source));
        }
    }
}
 public static class ext
{
    public static void CopyAllTo<T>(this T source, T target)
    {
        var type = typeof(T);
        foreach (var sourceProperty in type.GetProperties())
        {
            var targetProperty = type.GetProperty(sourceProperty.Name);
            targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
        }
        foreach (var sourceField in type.GetFields())
        {
            var targetField = type.GetField(sourceField.Name);
            targetField.SetValue(target, sourceField.GetValue(source));
        }
    }
}
黒涩兲箜 2024-10-08 12:03:04

您应该使用 AutoMapper 它是为此工作构建的。

You should use AutoMapper it was built for this job.

走过海棠暮 2024-10-08 12:03:04

尝试此链接中的描述:

.NET 反射 - 复制类属性

Try description in this link:

.NET Reflection - Copy Class Properties

稀香 2024-10-08 12:03:04

该代码应该适用于基本属性类型,但不确定它将如何适用于任何复杂的(列表、数组、自定义类)。不过应该是一个起点:

public class MyClass
{
  public int A { get; set; }
  public string B { get; set; }
}

private void button1_Click(object sender, EventArgs e)
{
  MyClass orig = new MyClass() { A = 1, B = "hello" };
  MyClass copy = new MyClass();

  PropertyInfo[] infos = typeof(MyClass).GetProperties();
  foreach (PropertyInfo info in infos)
  {
    info.SetValue(copy, info.GetValue(orig, null), null);
  }
  Console.WriteLine(copy.A + ", " + copy.B);
}

This code should work for basic property types, not sure how it'll go for anything complex (lists, arrays, custom classes). Should be a starting point though:

public class MyClass
{
  public int A { get; set; }
  public string B { get; set; }
}

private void button1_Click(object sender, EventArgs e)
{
  MyClass orig = new MyClass() { A = 1, B = "hello" };
  MyClass copy = new MyClass();

  PropertyInfo[] infos = typeof(MyClass).GetProperties();
  foreach (PropertyInfo info in infos)
  {
    info.SetValue(copy, info.GetValue(orig, null), null);
  }
  Console.WriteLine(copy.A + ", " + copy.B);
}
凯凯我们等你回来 2024-10-08 12:03:04

我知道 OP 没有要求将一种类型转换为另一种类型,但我的变体是我在startup.cs 中用于 DI 的变体,以解决云和本地开发环境之间配置不匹配的问题。我的本地类通常在幕后使用 Interface 类来映射配置。然后,我使用此方法复制仅名称匹配的属性。我没有检查属性类型,因为这些是配置。建议使用 AutoMapper。我不使用 AutoMapper,因为我们受到美国国防部对某些提供商的限制。仅使用 .NET 获得 ATO 就已经够难的了,我们不需要再悲伤了。

  using System.Linq;
  public static class PropertyCopy
  {
    public static void CopyAllTo<T,T1>(this T source, T1 target)
    {
      var type = typeof(T);
      var type1 = typeof(T1);
      foreach (var sourceProperty in type.GetProperties())
      {
        foreach (var targetProperty in type1.GetProperties()
          .Where(targetProperty => sourceProperty.Name == targetProperty.Name)
          .Where(targetProperty => targetProperty.SetMethod != null))
        {
          targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
        }
      }

      foreach (var sourceField in type.GetFields())
      {
        foreach (var targetField in type1.GetFields()
          .Where(targetField => sourceField.Name == targetField.Name))
        {
          targetField.SetValue(target, sourceField.GetValue(source));
        }
      }

    }
  }

I know the OP did not ask for a Type to another Type but my variant is one I use for DI in startup.cs for mismatches in configurations between cloud and local dev environment. My local class generally uses a Interface class behind the scenes to map the configurations. Then I use this method to copy properties where they match in name only. I am not checking property types since these are configurations. AutoMapper was suggested. I don't use AutoMapper because we are restricted by U.S. DOD to certain providers. Getting an ATO is hard enough just using .NET, we don't need any more grief.

  using System.Linq;
  public static class PropertyCopy
  {
    public static void CopyAllTo<T,T1>(this T source, T1 target)
    {
      var type = typeof(T);
      var type1 = typeof(T1);
      foreach (var sourceProperty in type.GetProperties())
      {
        foreach (var targetProperty in type1.GetProperties()
          .Where(targetProperty => sourceProperty.Name == targetProperty.Name)
          .Where(targetProperty => targetProperty.SetMethod != null))
        {
          targetProperty.SetValue(target, sourceProperty.GetValue(source, null), null);
        }
      }

      foreach (var sourceField in type.GetFields())
      {
        foreach (var targetField in type1.GetFields()
          .Where(targetField => sourceField.Name == targetField.Name))
        {
          targetField.SetValue(target, sourceField.GetValue(source));
        }
      }

    }
  }
不必了 2024-10-08 12:03:04

用非常简单的话来说:我们知道类是 C#.NET 中的引用类型,即当我们创建一个类的对象时,例如

Customer C1=new Customer();
C1.Id=1;
C1.Name="Rakesh";

C1(引用变量)存储在内存堆栈上,对象 new Customer() 存储在堆上。

因此,当我们将一个类复制到另一个类时,这基本上是您的问题,您可以执行如下操作:

Customer C2=C1;

执行上述操作会将 C1 引用变量复制到 C2 但为什么我写有关堆栈和堆的内容,因为使用 C2 引用变量您可以更改对象属性C1 和 C2 都指向 HEAP 中的同一个对象。就像

C2.Id=1;
C2.Name="Mukesh";

现在一样,如果您尝试访问 C1.Name,您将看到它更改为“Mukesh”。

In very simple terms: As we know Classes are reference types in C#.NET i.e. when we create a object of a class such as

Customer C1=new Customer();
C1.Id=1;
C1.Name="Rakesh";

Then C1(Reference variable) is stored on memory stack and object new Customer() is stored on Heap.

Hence when we copy a class into another class which is basically your question you can do something like below:

Customer C2=C1;

Doing above will copy the C1 Reference variable into C2 But why I wrote about Stack and Heap because using C2 reference variable you can change the object properties being both C1 and C2 pointing to same object in HEAP.Something Like

C2.Id=1;
C2.Name="Mukesh";

Now if you will try to access C1.Name you will see it is changed to "Mukesh".

流绪微梦 2024-10-08 12:03:04

你可以像这样使用 JsonConvert:

string jsonString = JsonConvert.SerializeObject(MyObject);
MyClass object = JsonConvert.DeserializeObject<MyClass>(jsonString);

you can use JsonConvert like this:

string jsonString = JsonConvert.SerializeObject(MyObject);
MyClass object = JsonConvert.DeserializeObject<MyClass>(jsonString);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文