gpt4 book ai didi

c# - 如何使公共(public)方法仅在类本身和拥有 C# 中的对象的类中可见?

转载 作者:太空狗 更新时间:2023-10-29 18:27:45 25 4
gpt4 key购买 nike

我和我的同事在研究获取委托(delegate)的调用列表时遇到了这个问题。如果您在类 X 中创建一个事件,那么您可以从该类中访问该事件的公共(public)方法。但是(请忽略诸如为什么你可以公开访问类成员的内容,这不是我们要问的!),如果我们有一个类 Y 实例化 X,并访问 X 中的事件,它不能调用事件的任何公共(public)方法,例如 GetInvocationList()。我们想知道这是如何运作的。这是一个代码示例(阅读评论以了解我们的意思):

    public class X
{
public delegate void TestMethod();

public event TestMethod testMethod;

private void rubbish()
{
// can access testMethod.GetInvocationList() fine here
testMethod.GetInvocationList();
}
}

public class Y
{
public Y()
{
X x = new X();
x.testMethod += this.test;

// here it says testMethod can only appear on the left hand side of += or -=
// why is this? (i.e. the below line is invalid)
x.testMethod.GetInvocationList();
}

public void test()
{
}
}

出于好奇,您是如何实现这一点的?提供此功能的原因是什么?

非常感谢 阿密特

最佳答案

这就是 event 关键字的作用;它是一个修饰符,用于限制对拥有类的订阅以外的操作。如果您删除 event 关键字,您最终将得到一个普通委托(delegate),类外的客户可以调用该委托(delegate),例如GetInvocationList() 方法。

blog post 中他们比较为普通委托(delegate)和事件生成的 IL 代码,它们的处理方式完全相同。 event 关键字是一个编译时修饰符,用于限制对委托(delegate)方法的访问。 (它还可以在界面中使用)。所有详细信息都在博客文章中。

关于c# - 如何使公共(public)方法仅在类本身和拥有 C# 中的对象的类中可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8726938/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com