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

sca*_*man 5 c# reflection inheritance jira copy-constructor

像这样:

    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
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

        public remoteStatusCounts(RemoteStatus r) : base(r) { //do stuff }
Run Code Online (Sandbox Code Playgroud)

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

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

        public remoteStatusCounts(RemoteStatus r) {
            RemoteStatus mBase = r;
            //do work
        }
Run Code Online (Sandbox Code Playgroud)

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

    public class remoteStatusCounts 
{
    public int statusCount;
    public RemoteStatus rStatus;
    public remoteStatusCounts(RemoteStatus r)
    {
        rStatus = r;
        statusCount = getStatusCount();
    }
}
Run Code Online (Sandbox Code Playgroud)

Fem*_*ref 1

是的,您可以这样做 - 但请注意,您可能会遇到必须单独处理的仅 getter 属性。

你可以用过Type.GetProperties(BindingsFlags)载来过滤它。

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

例子:

//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);
    }
}
Run Code Online (Sandbox Code Playgroud)