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