【问题标题】:Can reflection be used to instantiate an objects base class properties?可以使用反射来实例化对象基类属性吗?
【发布时间】:2011-03-05 14:10:50
【问题描述】:

像这样:

    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 个属性。我不想手动设置所有这些值,尤其是如果我的继承类只有几个额外的属性。

反思似乎暗示了答案。

我在Using inheritance in constructor (publix X () : y) 看到我可以调用基类构造函数(我想?如果我错了请纠正我),但是我的基类没有构造函数 - 它是从 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();
    }
}

【问题讨论】:

  • 或代码生成,但我宁愿不走那条路。
  • 注意:你的类名应该以大写字母开头。 </code-format-nazi>

标签: c# reflection inheritance jira copy-constructor


【解决方案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);
    }
}

【讨论】:

  • 怎么样?我不能在对象上调用 setValue。this.setValue(p.Name,r.getValue) 无法编译。
  • 您当然必须为此获取 Type 对象,使用 t.GetProperty(name) 获取相应的属性并对该对象执行 SetValue。
  • 编译如下: thisProperty.SetValue(this, p.GetValue(typeR,null),null);但随后它会引发运行时异常“对象与目标类型不匹配”
  • 不。不能在静态类上调用 getType()。 +1 距离更近。
  • 运行时异常 - “用户代码未处理 TargetException - 对象与目标类型不匹配。”感谢您为此工作-我真的对反射一无所知。我认为这应该是可能的,但我真的不知道。
【解决方案2】:

试试AutoMapper

【讨论】:

  • 甜蜜!我以前从未听说过 - 肯定会在某个时候派上用场!
猜你喜欢
  • 1970-01-01
  • 2014-10-09
  • 2012-06-22
  • 1970-01-01
  • 1970-01-01
  • 2015-11-28
  • 1970-01-01
  • 2010-09-13
  • 1970-01-01
相关资源
最近更新 更多