代码之家  ›  专栏  ›  技术社区  ›  scaryman

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

  •  5
  • scaryman  · 技术社区  · 14 年前

    这样地:

        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 }
    

    编辑 我可以想象两个有效的解决方案:上面概述的一个,和一些关键字,比如 this.baseClass 那是 type(baseclass) 像这样被操纵,作为一种指向 this . 所以, this.baseClass.name = "Johnny" 会和 this.name = "Johnny"

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

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

    编辑2 这个问题更像是一个思想上的练习,而不是一个实践上的练习——就我的目的而言,我可以很容易地做到这一点:(假设我的“基类”可以复制)

        public class remoteStatusCounts 
    {
        public int statusCount;
        public RemoteStatus rStatus;
        public remoteStatusCounts(RemoteStatus r)
        {
            rStatus = r;
            statusCount = getStatusCount();
        }
    }
    
    2 回复  |  直到 14 年前
        1
  •  1
  •   Femaref    14 年前

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

    你可以用 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);
        }
    }
    
        2
  •  2
  •   Jordão    14 年前

    尝试 AutoMapper .