【发布时间】:2011-01-14 00:32:11
【问题描述】:
我正在尝试使用 Microsoft 企业验证方法在我的实体中执行验证。在我的基类中,我有以下方法:
public class BaseEntity
{
public bool IsValid()
{
return Validate().IsValid;
}
public ValidationResults Validate()
{
return Validation.Validate<this.GetType()>(this);
}
这样做的问题是,即使 BaseEntity 的子类调用 IsValid,this.GetType() 总是返回 BaseEntity,而不是子类的类型。我不想为每个实体重写这段代码,因为这看起来很不像 OO。有没有其他方法可以做到这一点?
我确实有想法让受保护的变量 protected Type _validationType,并在每个实体中将其设置为该实体的 .GetType 值,但似乎必须有更好的方法来做到这一点。
更新
显然没关系。 this.GetType() 似乎像我希望的那样工作。不知道为什么以前没有。
我还更改了我的 Validate() 方法以使用以下代码:
return ValidationFactory.CreateValidator(this.GetType()).Validate(this);
【问题讨论】:
标签: c# validation inheritance subclass