C#:Child类可以限制对Parent类方法的访问吗?

3Pi*_*3Pi 3 c# inheritance

我需要两个略有不同的类,它们具有相同的成员,但其中一个类需要用户具有较少的交互可能性.我希望从第一个继承第二个类.
有没有办法限制从子类访问父方法,所以如果有人创建子对象,他们将无法访问某些父类方法(在父类中是公共的)?

Blo*_*ard 7

不,这就是原因:

class Animal { 
   public void Speak() { Console.WriteLine("..."); }
}

class Dog : Animal { 
   remove void Speak();  // pretend you can do this
}

Animal a = GetAnAnimal(); // who knows what this does

a.Speak();  // It's not known at compile time whether this is a Dog or not
Run Code Online (Sandbox Code Playgroud)


Sim*_*Var 6

你应该有一个基本抽象类来保存两个类的共同点,然后让其他两个类继承它并添加方法和属性等.

abstract class MyBaseClass
{
    public int SharedProperty { get; set; }

    public void SharedMethod()
    {
    }
}

class MyClass1 : MyBaseClass
{
    public void Method1()
    {
    }
}

class MyClass2 : MyBaseClass
{
    public void Method2()
    {
    }
}
Run Code Online (Sandbox Code Playgroud)

MyClass1有:SharedProperty,SharedMethod,和Method1.

MyClass2有:SharedProperty,SharedMethod,和Method2.