c#中的接口属性副本
我已经和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属性的值从一个类复制到另一个类。 这可能是在一个简单的单行语句中还是我仍然需要对每个语句进行属性到属性的分配? 我真的很惊讶这个看似简单的东西让我感到困惑……如果不可能以简洁的方式,有没有人有任何捷径他们用来做这种事情?
谢谢!
这没有任何一个class轮。
如果你做了很多,你可以研究某种forms的代码生成,也许使用T4模板和Reflection。
BTW COBOL对此有一个声明:移动相应的家庭工作。
这是一种与接口无关的方法:
public static class ExtensionMethods { public static void CopyPropertiesTo(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(b); Console.WriteLine(b); }
在您的情况下,如果您只想要复制一组接口属性,则可以执行以下操作:
((IAddress)home).CopyPropertiesTo(b);
您可以构建一个扩展方法:
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; //... }
Jimmy Bogard的AutoMapper对于这种映射操作非常有用。
我不相信有一个语言就绪解决方案(所有属性都需要有getter和setter)。
您可以使用复制(地址添加)方法将地址创建为抽象类。
或者,您可以使Home和Work具有IAddress,而不是扩展IAddress。 然后立即复制。
您需要创建一个方法来执行此操作
public void CopyFrom(IAddress source) { this.Address1 = source.Address1; this.Address2 = source.Address2; this.City = source.city; }
您可以在每个类上使用IAddress构建一个构造函数,并在其中填充已实现的成员。
例如
public WorkAddress(Iaddress address) { Line1 = IAddress.Line1; ... }
为了可维护性,使用reflection来获取属性名称。
HTH,
担
如果您将家庭和工作地址的公共部分封装到一个单独的类中,它可能会让您的生活更轻松。 然后您可以简单地复制该属性。 这对我来说似乎更好的设计。
或者,您可以将具有reflection和属性的解决方案组合在一起,其中将一个对象中的属性值复制到另一个对象中的匹配(和标记)属性。 当然,这也不是单线解决方案,但如果你拥有大量属性,它可能比其他解决方案更快,更易于维护。
- Silverlight中附加和非附加依赖属性的区别
- 使用Visual C#2010 Express在C#项目中添加引用“SHDocVw”
- 图表无法正确读取日期时间变量c#秒
- 如何测试使用BackgroundWorker加载的ViewModel?
- 由Windows.Security.Cryptography.CryptographicBuffer中的方法生成的IBuffer对象是否具有安全function?
- WCF Web服务错误:“服务端点绑定不使用HTTP协议”?
- 将自定义对象列表显示为PropertiesGrid中的下拉列表
- 如何在MVC3中的TemplateEditor中向模型属性添加validation属性
- 如何使RawPrinterHelper在XPS_PATH和RAW数据类型中都有效?