从基类中的派生类获取属性 [英] Get properties from derived class in base class

查看:70
本文介绍了从基类中的派生类获取属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How do I get properties from derived class in base class?

基类:

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"属性吗?

In this example - can I get the "Name" property from ServerItem class while in BaseModel class?

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

I'm trying to implement model validation, as described here: http://weblogs.asp.net/marianor/archive/2009/04/17/wpf-validation-with-attributes-and-idataerrorinfo-interface-in-mvvm.aspx

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

I figured that if I create some base model with (almost) all of the validation magic in it, and then extend that model, it will be okay...

推荐答案

如果两个类在同一个程序集中,你可以试试这个:

If both classes are in the same assembly, you can try this:

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

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

This will give you all the properties of all the subclasses of BaseClass.

这篇关于从基类中的派生类获取属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆