inheritance-prevention

Preventing methods from being inherited

爷,独闯天下 提交于 2019-12-07 05:13:46
问题 I have a base class Foo that is concrete and contains 30 methods which are relevant to its subclasses. Now I've come across a situation that is specific only to the base class,and I want to create a method that cannot be inherited, is this possible? Class Foo { /* ... inheritable methods ... */ /* non-inheritable method */ public bool FooSpecificMethod() { return true; } } Class Bar : Foo { /* Bar specific methods */ } var bar = new Bar(); bar.FooSpecificMethod(); /* is there any way to get

Preventing methods from being inherited

随声附和 提交于 2019-12-05 11:08:55
I have a base class Foo that is concrete and contains 30 methods which are relevant to its subclasses. Now I've come across a situation that is specific only to the base class,and I want to create a method that cannot be inherited, is this possible? Class Foo { /* ... inheritable methods ... */ /* non-inheritable method */ public bool FooSpecificMethod() { return true; } } Class Bar : Foo { /* Bar specific methods */ } var bar = new Bar(); bar.FooSpecificMethod(); /* is there any way to get this to throw compiler error */ EDIT I'm not sure if I was clear originally. I do understand the

How to hide (remove) a base class's methods in C#? [duplicate]

▼魔方 西西 提交于 2019-11-27 20:10:58
This question already has an answer here: C# - Can publicly inherited methods be hidden (e.g. made private to derived class) 10 answers The essence of the problem is, given a class hierarchy like this: class A { protected void MethodToExpose() {} protected void MethodToHide(object param) {} } class B : A { new private void MethodToHide(object param) {} protected void NewMethodInB() {} } class C : B { public void DoSomething() { base.MethodToHide("the parameter"); // This still calls A.MethodToHide() base.MethodToExpose(); // This calls A.MethodToExpose(), but that's ok base.NewMethodInB(); } }

How to hide (remove) a base class's methods in C#? [duplicate]

∥☆過路亽.° 提交于 2019-11-26 20:12:57
问题 This question already has answers here : C# - Can publicly inherited methods be hidden (e.g. made private to derived class) (10 answers) Closed 4 years ago . The essence of the problem is, given a class hierarchy like this: class A { protected void MethodToExpose() {} protected void MethodToHide(object param) {} } class B : A { new private void MethodToHide(object param) {} protected void NewMethodInB() {} } class C : B { public void DoSomething() { base.MethodToHide("the parameter"); // This