c# - 从基类中的派生类获取属性

标签 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 类获取“名称”属性吗?

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

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

最佳答案

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

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

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

关于c# - 从基类中的派生类获取属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15834403/

相关文章:

c# - 如何从 C# 类计算类级依赖项

javascript - JS中如何暴露成员变量的public方法

python - 在 Python OOP 中是否可以从导入时包含的模块中初始化一个类

c# - 我可以指定一个 dll 以在 Powershell 中使用 New-Object 吗?

c# - 在 Wpf 中,如何将命令从按钮发送到子控件?

c# - 实现组合的正确方法(带有接口(interface)的组合)

json - 动态创建某种类型的结构并将 JSON 解码到该实例中

Java,获取包含类的类对象,而不是运行时类

c# - 使用反射设置索引属性的值

c# - 当 .Count() 大于零时从 .Select() 获取 NullReferenceException LINQ to XML