从基类中的派生类获取属性

时间:2013-04-05 12:47:51

标签: c# oop reflection

如何从基类派生类中获取属性?

基类:

public abstract class BaseModel {
    protected static readonly Dictionary<string, Func<BaseModel, object>>
            _propertyGetters = typeof(BaseModel).GetProperties().Where(p => _getValidations(p).Length != 0).ToDictionary(p => p.Name, p => _getValueGetter(p));
}

派生类:

public class ServerItem : BaseModel, IDataErrorInfo {
    [Required(ErrorMessage = "Field name is required.")]
    public string Name { get; set; }
}

public class OtherServerItem : BaseModel, IDataErrorInfo {
    [Required(ErrorMessage = "Field name is required.")]
    public string OtherName { get; set; }

    [Required(ErrorMessage = "Field SomethingThatIsOnlyHereis required.")]
    public string SomethingThatIsOnlyHere{ get; set; }
}

在这个例子中 - 我可以在BaseModel类中从ServerItem类获取“Name”属性吗?

编辑: 我正在尝试实现模型验证,如下所述: http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx

我想如果我用(几乎)所有的验证魔法创建一些基础模型,然后扩展该模型,那就没关系......

7 个答案:

答案 0 :(得分:7)

如果您要求派生类必须实现方法或属性,则应将该方法或属性作为抽象声明引入基类。

例如,对于您的Name属性,您将添加到基类:

public abstract string Name { get; set; }

然后任何派生类必须实现它,或者是抽象类本身。

Name属性的抽象版本添加到基类后,您将能够在基类的构造函数中的之外的任何位置的基类中访问它。 / p>

答案 1 :(得分:5)

如果两个类都在同一个程序集中,您可以尝试:

Assembly
    .GetAssembly(typeof(BaseClass))
    .GetTypes()
    .Where(t => t.IsSubclassOf(typeof(BaseClass))
    .SelectMany(t => t.GetProperties());

这将为您提供BaseClass的所有子类的所有属性。

答案 2 :(得分:4)

如果你必须从基类中逐字地获取派生类的属性,你可以使用Reflection,例如 - 像这样......

using System;
public class BaseModel
{
    public string getName()
    {
        return (string) this.GetType().GetProperty("Name").GetValue(this, null);
    }
}

public class SubModel : BaseModel
{
    public string Name { get; set; }
}

namespace Test
{
    class Program
    {
        static void Main(string[] args)
        {
            SubModel b = new SubModel();
            b.Name = "hello";
            System.Console.Out.WriteLine(b.getName()); //prints hello
        }
    }
}

不建议这样做,你很可能应该像马修所说的那样重新考虑你的设计。

至于不向基类抛出属性 - 您可以尝试将基类解耦并将类派生为不相关的对象,并通过构造函数传递它们。

答案 3 :(得分:1)

好的,我解决了这个问题与这篇文章的作者略有不同:http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx

public abstract class BaseModel : IDataErrorInfo {
    protected Type _type;
    protected readonly Dictionary<string, ValidationAttribute[]> _validators;
    protected readonly Dictionary<string, PropertyInfo> _properties;

    public BaseModel() {
        _type = this.GetType();
        _properties = _type.GetProperties().ToDictionary(p => p.Name, p => p);
        _validators = _properties.Where(p => _getValidations(p.Value).Length != 0).ToDictionary(p => p.Value.Name, p => _getValidations(p.Value));
    }

    protected ValidationAttribute[] _getValidations(PropertyInfo property) {
        return (ValidationAttribute[])property.GetCustomAttributes(typeof(ValidationAttribute), true);
    }

    public string this[string columnName] {
        get {
            if (_properties.ContainsKey(columnName)) {
                var value = _properties[columnName].GetValue(this, null);
                var errors = _validators[columnName].Where(v => !v.IsValid(value)).Select(v => v.ErrorMessage).ToArray();
                return string.Join(Environment.NewLine, errors);
            }

            return string.Empty;
        }
    }

    public string Error {
        get { throw new NotImplementedException(); }
    }
}

也许它会帮助某人。

答案 4 :(得分:0)

从BaseModel扫描程序集中所有继承的类,并创建如下字典:

Dictionary<Type, Dictionary<string, Func<BaseModel, object>>>

答案 5 :(得分:0)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TESTNEW
{
   public abstract class BusinessStructure
    {
       public BusinessStructure()
       { }

       public string Name { get; set; }
   public string[] PropertyNames{
       get
       { 
                System.Reflection.PropertyInfo[] Pr;
                System.Type _type = this.GetType();
                Pr = _type.GetProperties();
                string[] ReturnValue = new string[Pr.Length];
                for (int a = 0; a <= Pr.Length - 1; a++)
                {
                    ReturnValue[a] = Pr[a].Name;
                }
                return ReturnValue;
       }
   }

}


public class MyCLS : BusinessStructure
   {
       public MyCLS() { }
       public int ID { get; set; }
       public string Value { get; set; }


   }
   public class Test
   {
       void Test()
       {
           MyCLS Cls = new MyCLS();
           string[] s = Cls.PropertyNames;
           for (int a = 0; a <= s.Length - 1; a++)
           {
            System.Windows.Forms.MessageBox.Show(s[a].ToString());
           }
       }
   }
}

答案 6 :(得分:0)

通过在基类中创建虚拟属性并将覆盖属性转换为派生类来解决此问题的另一种方法。

public class Employee
{
    public virtual string Name {get; set;}
}

public class GeneralStaff
{
    public override string Name {get; set;}
}

class Program
{
        static void Main(string[] args)
        {
            Employee emp = new GeneralStaff();
            emp.Name = "Abc Xyz";
            //---- More code follows----            
        }
}