虚拟类中的抽象方法 [英] abstract method in a virtual class

查看:104
本文介绍了虚拟类中的抽象方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含大量虚方法的c#类,其中某些方法本质上是抽象的(它们在子类中完全实现,而基类为空).

I have a c# Class that has lots of virtual methods, some of these methods are essentially abstract ( they are fully implemented in subclasses and the base class is empty).

要使其编译,我在基类中引发了InvalidOperationException并带有注释,说明应该做什么.这感觉很脏.

To get it to compile i am throwing an InvalidOperationException in the base class with a comment on what should be done. This just feels dirty.

有没有更好的方法来设计我的课程?

Is there a better way to design my classes?

它是针对将在加拿大运行的应用程序的中间层,一半的方法是通用的,因此是虚拟的.一半的方法是针对特定省份的.

edit: It is for the middle tier of an application that will be ran in canada, half of the methods are generic hence the virtual. and half of the methods are province specific.

Public class PersonComponent() 
{

 public GetPersonById(Guid id) {
  //Code to get person - same for all provinces
 }

 Public virtual DeletePerson(Guid id) {
  //Common code
 }

 Public virtual UpdatePerson(Person p) {
  throw new InvalidOperation("I wanna be abstract");
 }

Public Class ABPersonComponent : PersonComponent
{
    public override DeletePerson(Guid id) 
    {
       //alberta specific delete code
    }

    public override UpdatePerson(Person p) 
    {
       //alberta specific update codecode
    }

}

希望这很有道理

推荐答案

考虑您的对象层次结构.是否要为所有派生类共享通用代码,然后在基类中实现基本功能.

Think about your object hierarchy. Do you want to share common code for all your derived classes, then implement base functionality in the base class.

共享基本代码时,请注意模板模式.使用公共方法并将其链接到具有核心/共享实现的受保护的虚拟方法.以"Core"结束共享的实现方法名.

When having shared base code, please notice the Template pattern. Use a public method and chain it to a protected virtual method with the core/shared implementation. End the shared implementation methodname with "Core".

例如:

public abstract class BaseClass
{
    protected virtual void DeletePersonCore(Guid id)
    {
        //shared code
    }

    public void DeletePerson(Guid id)
    {
        //chain it to the core
        DeletePersonCore(id);
    }
}

public class DerivedClass : BaseClass
{
    protected override void DeletePersonCore(Guid id)
    {
        //do some polymorphistic stuff

        base.DeletePersonCore(id);
    }
}

public class UsageClass
{
    public void Delete()
    {
        DerivedClass dc = new DerivedClass();

        dc.DeletePerson(Guid.NewGuid());
    }
}

这篇关于虚拟类中的抽象方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆