是的,您可以这样做-但是请注意,您可能会遇到一些getter-only属性,这些属性必须单独处理。
你可以用
Type.GetProperties(BindingsFlags)
超载。
注意:您可能应该研究代码生成(T4是一个想法,因为它是随VS 2008/2010一起交付的),因为反射可能会影响运行时的执行速度。使用代码生成,您可以轻松地处理这项繁琐的工作,并且仍然拥有相同的运行时等,比如手动键入它。
例子:
public static T Cast<T>(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);
}
}