C# 中的接口属性复制

2024-06-25

我已经使用 C# 多年了,但刚刚遇到了这个困扰我的问题,我真的不知道如何提出这个问题,所以,举个例子!

public interface IAddress
{
  string Address1 { get; set; }
  string Address2 { get; set; }
  string City { get; set; }
  ...
}

public class Home : IAddress
{
  // IAddress members
}

public class Work : IAddress
{
  // IAddress members
}

我的问题是,我想将 IAddress 属性的值从一个类复制到另一个类。这可以在简单的一行语句中实现吗?还是我仍然需要对每个语句进行属性到属性的分配?事实上,我很惊讶这个看似简单的事情让我难住了……如果不可能以简洁的方式实现,那么有人有任何捷径可以用来做这类事情吗?

Thanks!


这是一种与接口无关的方法:

public static class ExtensionMethods
{
    public static void CopyPropertiesTo<T>(this T source, T dest)
    {
        var plist = from prop in typeof(T).GetProperties() where prop.CanRead && prop.CanWrite select prop;

        foreach (PropertyInfo prop in plist)
        {
            prop.SetValue(dest, prop.GetValue(source, null), null);
        }
    }
}

class Foo
{
    public int Age { get; set; }
    public float Weight { get; set; }
    public string Name { get; set; }
    public override string ToString()
    {
        return string.Format("Name {0}, Age {1}, Weight {2}", Name, Age, Weight);
    }
}

static void Main(string[] args)
{
     Foo a = new Foo();
     a.Age = 10;
     a.Weight = 20.3f;
     a.Name = "Ralph";
     Foo b = new Foo();
     a.CopyPropertiesTo<Foo>(b);
     Console.WriteLine(b);
 }

在您的情况下,如果您只想复制一组接口属性,您可以执行以下操作:

((IAddress)home).CopyPropertiesTo<IAddress>(b);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 中的接口属性复制 的相关文章

随机推荐