c# - 如何确保只能从特定类调用类方法?

标签 c# oop

public class A
{
    private void MethodA(){}
}

public class B
{
    private void MethodB() { }
}

public class C
{
    private void MethodC() { }
}

我想确保只能从 MethodB 调用 MethodA。其他方法永远不能调用MethodA

最佳答案

制造MethodA protected 并像这样使用继承:

public class A
{
    protected void MethodA()
    {
    }
}

public class B : A
{
    private void MethodB()
    {
        //MethodA is accessible just here
    }
}

public class C
{
    private void MethodC()
    {
        //MethodA is not accessible here
    }
}

但是,如果您不想使用继承并希望所有类都在同一程序集中,则只能嵌套类 B类内A并保留MethodA私有(private)的。像这样:

public class A
{
    private void MethodA()
    {
    }
    public class B
    {
        private void MethodB()
        {
            A a = new A();
            a.MethodA();
        }
    }
}

public class C
{
    private void MethodC()
    {
        //MethodA is not accessible here
    }
}

public class D : A
{
    private void MethodC()
    {
        //MethodA is not accessible here
    }
}

关于c# - 如何确保只能从特定类调用类方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969018/

相关文章:

c# - 条件预订系统的最佳设计模式

c# - 泛型可以嵌套在类定义中吗

c# - 是否可以安全地序列化非托管类型?

c# - 删除其他表中没有引用的行

c# - 具有空方法的接口(interface)与抽象类

python - 为什么不应该在 python 中动态生成变量名?

c# - 使用标题信息获取图像的尺寸

c# - 如何使用带有存储过程和参数的 DataAdapter

swift - Swift 中的 BaseViewController 和 UIPageViewController

C# (OOP) 嵌套业务对象