委托的封装问题? [英] Encapsulation issue with delegates?

查看:80
本文介绍了委托的封装问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道为什么这行得通吗?

I'm wondering why this works?

例如,我有一些 executor类,如下所示:

For example I have some executor class that looks like so:

public class Executor
{
    public void Execute(Action action)
    {
        action();
    }
}

现在,我有一些需要执行的类,如下所示:

Now I have some need to be executed class that looks like:

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

    private void DoSomething()
    {
        // do stuff private
    }
}

我的问题是为什么这是可行的,因为我通过了私有方法其他课程?

My question is why this is work's I pass a private method to other class?

这不是封装问题吗?

推荐答案

否,这不违反封装.

首先:类本身是决定将委托分发给其私有方法之一的东西!该类具有访问其私有方法的权限,并且如果选择将对它的引用传递给该方法的可访问性域之外,则这完全在其权限之内.

First off: the class itself is the thing that decided to hand out a delegate to one of its private methods! The class has access to its private methods and if it chooses to hand a reference to one to code outside of the accessibility domain of that method, that's perfectly within its rights.

第二:方法的可访问域并不限制可以在何处调用该方法. 它限制了可以按名称查找方法的地方.类Executor从未使用 name DoSomething来调用私有方法.它使用名称action.

Second: the accessibility domain of a method doesn't restrict where the method can be called. It restricts where the method can be looked up by name. Class Executor is never using the name DoSomething to invoke the private method. It's using the name action.

这篇关于委托的封装问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆