将所有类字段和属性复制到另一个类

Rom*_*key 4 c#

我有一个通常包含字段,属性的类。我要实现的不是此:

class Example
{
    public string Field = "EN";
    public string Name { get; set; }
    public int? Age { get; set; }
    public List<string> A_State_of_String { get; set; }
}

public static void Test()
{
    var c1 = new Example
    {
        Name = "Philip",
        Age = null,
        A_State_of_String = new List<string>
        {
            "Some Strings"
        }
    };
    var c2 = new Example();

    //Instead of doing that
    c2.Name = string.IsNullOrEmpty(c1.Name) ? "" : c1.Name;
    c2.Age = c1.Age ?? 0;
    c2.A_State_of_String = c1.A_State_of_String ?? new List<string>();

    //Just do that
    c1.CopyEmAll(c2);
}
Run Code Online (Sandbox Code Playgroud)

我想出了什么,但没有按预期工作。

public static void CopyEmAll(this object src, object dest)
{
    if (src == null) {
        throw new ArgumentNullException("src");
    }

    foreach (PropertyDescriptor item in TypeDescriptor.GetProperties(src)) {
        var val = item.GetValue(src);
        if (val == null) {
            continue;
        }
        item.SetValue(dest, val);
    }
}
Run Code Online (Sandbox Code Playgroud)

问题:

  • 虽然我检查为空,但似乎绕过它。
  • 似乎没有复制字段。

笔记:

  • 我不想使用AutoMapper一些技术问题。
  • 我希望该方法复制值而不创建新对象。[只是模仿我在示例中说明的行为]
  • 我希望函数是递归的[如果该类包含另一个类,它也会将其值复制到最内部的那个类中]
  • 除非我允许,否则不想复制null或空值。
  • 复制所有字段,属性甚至事件。

the*_*000 6

基于Leo的答案,但使用泛型并复制字段:

public void CopyAll<T>(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));
    }       
}
Run Code Online (Sandbox Code Playgroud)

然后:

CopyAll(f1, f2);
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

6671 次

最近记录:

8 年,8 月 前