c# - 如何在继承中授予对选择性类方法的访问权限?

标签 c# oop inheritance

我们有一个基类 A,它包含 6 个公共(public)方法:

public class A
{ 
 public void method1()
 {
  // Implementation
 }

 public void method2()
 {
   // Implementation
 }
 .
 . 
 .
 .
 public void method6()
 {
  // Implementation
 }
}

我们有两个继承自 A 的子类 B 和 C。我怎样才能实现它,使 B 类只能访问 method1()、method2()、method3() 而 C 类只能访问 method4 (),方法5(),方法6()??

最佳答案

您无法阻止某些东西使用公共(public)类 A 方法,但您绝对可以通过正确使用接口(interface)来隐藏它们。

interface IAOne 
{
    void method1();
    void method2();
    void method3();
}

interface IATwo 
{
    void method4();
    void method5();
    void method6();
}

class A : IAOne, IATwo
{
    void method1() { }
    void method2() { }
    void method3() { }
    void method4() { }
    void method5() { }
    void method6() { }
}

现在你有了类 B,它永远不需要知道 AA 的方法。它只知道 IAOne 接口(interface)。 B 现在还可以重新公开任何方法(甚至重新实现接口(interface))并将这些方法的实现委托(delegate)给 A

class B : IAOne 
{
    private IAOne _a;
    public B(IAOne a) { _a = a; }

    void method1() { _a.method1(); }
    void method2() { _a.method2(); }
    void method3() { _a.method3(); }
}

关于c# - 如何在继承中授予对选择性类方法的访问权限?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42555291/

相关文章:

c# - 在 XamlParse 上崩溃部署的应用程序

java - 成员函数返回/获取实例变量

c++ - 将对象指针转换为 char 数组

javascript - Javascript 中的继承

c# - Windows 下 C++ 和 C# 中的套接字无法正常工作

c# - 如何使用 xunit test 比较两个列表

c# - Azure Data Lake 中的 U-SQL 查询错误

java - java中OOP概念和设计模式的区别(哪个更重要)

oop - 知道何时对领域关系进行建模以及如何处理上下文关系

c++ - 所有继承同一类的不同对象的单个容器