Can reflection be used to instantiate an objects base class properties?

烂漫一生 提交于 2019-12-05 10:09:39

Yes, you can do this - be aware though, that you might run into getter-only properties which you have to deal with seperately.

You can filter it with the Type.GetProperties(BindingsFlags) overload.

Note: You probably should look into code generation (T4 would be an idea, as it is delivered with vs 2008/2010), because reflection could have runtime-implications like execution speed. With codegeneration, you can easily handle this tedious work and still have the same runtime etc like typing it down manually.

Example:

//extension method somewhere
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);
    }
}

Try AutoMapper.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!