我已经和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
}
Run Code Online (Sandbox Code Playgroud)
我的问题是,我想将IAddress属性的值从一个类复制到另一个类.这可能是在一个简单的单行语句中还是我仍然需要对每个语句进行属性到属性的分配?我真的很惊讶这个看似简单的东西让我感到困惑......如果不可能以简洁的方式,有没有人有任何捷径他们用来做这种事情?
谢谢!
pli*_*nth 19
这是一种与接口无关的方法:
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);
}
Run Code Online (Sandbox Code Playgroud)
在您的情况下,如果您只想要复制一组接口属性,则可以执行以下操作:
((IAddress)home).CopyPropertiesTo<IAddress>(b);
Run Code Online (Sandbox Code Playgroud)
Joe*_*orn 12
您可以构建一个扩展方法:
public static void CopyAddress(this IAddress source, IAddress destination)
{
if (source is null) throw new ArgumentNullException("source");
if (destination is null) throw new ArgumentNullException("destination");
//copy members:
destination.Address1 = source.Address1;
//...
}
Run Code Online (Sandbox Code Playgroud)
对于这一点,没有任何一言一行。
如果您经常这样做,您可以研究某种形式的代码生成,也许使用 T4 模板和反射。
BTW COBOL对此有一个声明:MOVE CORRESPONDING HOME TO WORK。