代表的封装问题?

Iam*_*ker 4 c# oop encapsulation

我想知道为什么这个有效?

例如,我有一些看起来像这样的执行器类:

public class Executor
{
    public void Execute(Action action)
    {
        action();
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我有一些需要被执行的类看起来像:

public class NeedToBeExecuted
{
    public void Invoke()
    {
        Executor executor = new Executor();
        executor.Execute(DoSomething);
    }

    private void DoSomething()
    {
        // do stuff private
    }
}
Run Code Online (Sandbox Code Playgroud)

我的问题是为什么这是工作我将私有方法传递给其他类

这不是封装问题吗?

Eri*_*ert 6

不,这不违反封装.

首先:类本身就是决定将委托分发给其私有方法的东西!该类可以访问其私有方法,如果它选择将一个引用传递给该方法的可访问域之外的代码,则完全在其权限范围内.

第二:方法的可访问性域不限制可以调用方法的位置. 它限制了可以按名称查找方法的位置.类Executor永远不会使用该名称 DoSomething来调用私有方法.它正在使用这个名字action.