abstract method in a virtual class

2019-04-10 16:22发布

问题:

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).

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
    }

}

hope this makes sense

回答1:

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.

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".

For example:

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());
    }
}


回答2:

Mark the base class as abstract, as well as the methods that have no implementation.

Like so

public abstract class BaseClass
{

    public abstract void AbstractMethod();
}

public class SubClass: BaseClass
{
    public override void AbstractMethod()
    {
        //Do Something
    }
}

You can't have abstract methods outside of an abstract class. Marking a class as abstract means you won't be able to instantiate it. But then it doesn't make any sense to. What are you going to do with a class that doesn't implement the methods anyway?

Edit: From looking at your class, yeah I'd make PersonComponent abstract along with the UpdatePerson method. Either that, or if UpdatePerson just doesn't do anything for a PersonComponent keep it as is, but make the UpdatePerson method empty for PersonComponent.