提供通用和虚拟成员的抽象/虚拟成员派生组合功能 - C#
我以前做过这个 - 只是不记得技巧了。
如果我有一个抽象类:
公共抽象类Post
和一组派生类:
公共类照片:Post >
我想强制派生类实现名为Validate()的方法,但同时在核心验证>岗位级别。
我可以在 Post 中创建一个方法:public abstract void Validate(),这将强制派生类实现该方法,但是我如何执行 后(基础)验证?
最终的结果是我希望能够做到这一点:
public class BLL
{
public void AddPost(Post post)
{
post.Validate(); // includes "Post" validation, any deriving validation.
repository.Add(post);
}
}
我该怎么做?
I've done this before - just can't remember the trick.
If i have an abstract class:
public abstract class Post
And a set of deriving classes:
public class Photo : Post
I want to force the deriving classes to implement a method called Validate(), but at the same time providing core validation at the Post level.
I can create a method: public abstract void Validate() in Post, which would force the deriving classes to implement the method, but then how do i perform the Post (base) validation?
The end result is i want to be able to do this:
public class BLL
{
public void AddPost(Post post)
{
post.Validate(); // includes "Post" validation, any deriving validation.
repository.Add(post);
}
}
How can i do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这就是您想要的:
这将强制基类实现验证技术,并且外部用户将调用基类 Validate。
不可能使方法抽象并提供默认实现。
Here is what you want:
This will force base classes to implement a validation technique, and the base Validate will get called by external users.
It is impossible to make a method abstract, and provide a default implementation.
在基类中创建一个公共模板方法,并让它调用派生类验证方法:
这会强制派生类实现该方法,但为 Post 类提供通用验证逻辑。请注意,Validate() 本身并不是虚拟的。这比强制派生类必须记住调用 base.Validate() 更安全。
Create a public template method in the base class and have it call the derived class validation method:
This forces derived classes to implement the method, but provides common validation logic for the Post class. Note that Validate() is not virtual itself. This is safer than forcing derived classes to have to remember to call base.Validate().