我的同事和我在研究获取委托的调用列表时遇到了这个问题。 如果你在类X中创建一个事件,那么你可以在该类中访问该事件的公共方法。 但是(并且请忽略诸如为什么你有公共访问类成员的东西,这不是我们要求的东西!),如果我们有一个类Y实例化X,并访问X中的事件,它不能调用任何公共方法,例如事件的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() { } }出于好奇,你如何实现这一点,并且这个功能可用的原因是什么?
非常感谢阿米特
My colleague and I came across this when looking into getting the invocation list of a delegate. If you create an event in say class X, then you can access the public methods of the event fine from within that class. But (and please ignore stuff like why you'd have public access to class members, this isn't what we're asking!), if we have a class Y instantiating X, and accessing the event within X, it can't call any of the public methods such as GetInvocationList() of the event. We wanted to know how this works. Here is a code sample (read the comments to see what we mean):
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() { } }Out of curiosity how do you achieve this, and what's the reason for having this feature avaialble?
Many Thanks Amit
最满意答案
event关键字就是这样做的; 它是一种限制操作,而不是订阅拥有的类。 如果你删除了event关键字,你最终会得到一个普通的委托,即类之外的客户端可以调用例如GetInvocationList()方法。
在博客文章中,他们将生成的IL代码与普通委托和事件进行比较,处理方式完全相同。 event关键字是一个编译时修饰符,它限制对委托方法的访问。 (它也可以在接口中使用)。 所有的细节都在博客文章中。
That's what the event keyword does; it is a modifier that restricts operations other than subscription to the owning class. If you remove the event keyword you will end up with a plain delegate that clients outside the class can call e.g. the GetInvocationList() method on.
In a blog post they compare the generated IL code for a plain delegate and an event and it is handled exactly the same. The event keyword is a compile-time modifier that restricts access to the methods of the delegate. (It also enables use in interfaces). All the details are in the blog post.
更多推荐
发布评论