Is there way for a class to 'remove' metho

2019-02-05 16:20发布

问题:

Is there way for a class to 'remove' methods that it has inherited?

E.g. if I don't want my class to have a ToString() method can I do something so that it is no longer available?

回答1:

No - this would violate Liskov's Substitution Principle. You should always be able to use an instance of a subtype as if it were an instance of a supertype.

Don't forget that a caller may only be aware of your type "as" the base type or an interface. Consider this code:

object foo = new TypeWithToStringRemoved();
foo.ToString();

That would have to compile, wouldn't it? Now what would you expect to happen at execution time?

Now for ToString, GetHashCode, Equals and GetType there's no way to avoid having them in the first place - but usually if there are methods you want to "remove" from a base type, that suggests you shouldn't be inheriting from it in the first place. Personally I find the role of inheritance is somewhat overplayed in object oriented programming: where it's useful it's really useful, but generally I prefer composition over inheritance, and interfaces as a form of abstraction rather than base classes.



回答2:

You can throw a NotSupportedException, mark it as Obsolete and use EditorBrowsable:

[EditorBrowsable( EditorBrowsableState.Never )]
[Obsolete( "...", false )]
void YourMethod()
{
    throw new NotSupportedException( "..." );
}

EDIT:
As pointed out by others: I describe a way to "disable" methods, but you have to think about carefully, where you want to use this. Especially throwing exceptions can be a very dangerous thing.



回答3:

As others pointed out, you can't "remove" a method, but if you feel it has wronged you in some way you can hide it in your derived class.

From Microsoft's documentation (now retired):

class Base
{
   public static void F() {}
}
class Derived: Base
{
   new private static void F() {}   // Hides Base.F in Derived only
}
class MoreDerived: Derived
{
   static void G() { F(); }         // Invokes Base.F
}


回答4:

Short awnser, NO as all classes inherit from object and object has this method.