可以使用reflection来实例化对象基类属性吗?

像这样:

public class remoteStatusCounts : RemoteStatus { public int statusCount; public remoteStatusCounts(RemoteStatus r) { Type t = r.GetType(); foreach (PropertyInfo p in t.GetProperties()) { this.property(p) = p.GetValue(); //example pseudocode } } } 

这个例子有点简单(它来自Jira API – RemoteStatus有4个属性),但想象一下基类有30个属性。 我不想手动设置所有这些值,特别是如果我的inheritance类只有一些额外的属性。

反思似乎暗示了一个答案。

我在构造函数(publix X():y)中看到了使用inheritance ,我可以调用基类构造函数(我认为?如果我错了,请纠正我),但我的基类没有构造函数 – 它源于jira wsdl

  public remoteStatusCounts(RemoteStatus r) : base(r) { //do stuff } 

编辑我可以想象2个有效的解决方案:上面概述的那个,以及某种像this.baseClass这样的关键字,它是type(baseclass)并且这样操作,作为一种指向this的指针。 所以, this.baseClass.name = "Johnny"this.name = "Johnny"完全相同

对于所有意图和目的,让我们假设基类有一个复制构造函数 – 也就是说,这是有效的代码:

  public remoteStatusCounts(RemoteStatus r) { RemoteStatus mBase = r; //do work } 

edit2这个问题更多的是一个思想练习而不是一个实际的 – 为了我的目的,我可以轻松地做到这一点:(假设我的“基类”可以复制)

  public class remoteStatusCounts { public int statusCount; public RemoteStatus rStatus; public remoteStatusCounts(RemoteStatus r) { rStatus = r; statusCount = getStatusCount(); } } 

是的,你可以做到这一点 – 但要注意,你可能遇到只有getter的属性,你必须单独处理。

您可以使用Type.GetProperties(BindingsFlags)重载来过滤它。

注意:您可能应该研究代码生成(T4将是一个想法,因为它与vs 2008/2010一起提供),因为reflection可能具有运行时影响,如执行速度。 使用代码生成,您可以轻松处理这种繁琐的工作,并且仍然具有相同的运行时等,例如手动输入。

例:

 //extension method somewhere public static T Cast(this object o) { return (T)o; } public remoteStatusCounts(RemoteStatus r) { Type typeR = r.GetType(); Type typeThis = this.GetType(); foreach (PropertyInfo p in typeR.GetProperties()) { PropertyInfo thisProperty = typeThis.GetProperty(p.Name); MethodInfo castMethod = typeof(ExMethods).GetMethod("Cast").MakeGenericMethod(p.PropertyType); var castedObject = castMethod.Invoke(null, new object[] { p.GetValue(r, null) }); thisProperty.SetValue(this, castedObject, null); } } 

试试AutoMapper 。