如何在基类中获取派生类的属性?
基类:
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/