从外部类调用私有事件处理程序
我有两节课。 一个类(比如 A)在 c'tor 中使用一个文本框。并使用私有事件处理程序方法注册 TextChanged 事件。 第二类(比如 B)通过提供文本框创建 A 类的对象。
如何从B类调用A类的私有事件处理程序?
它还注册 MouseClick 事件。
有什么方法可以调用私有事件处理程序吗?
i've two classes.
One class (say A) takes a textbox in c'tor. and registers TextChanged event with private event-handler method.
2nd class (say B) creates the object of class A by providing a textbox.
how to invoke the private event handler of class A from class B?
it also registers the MouseClick event.
is there any way to invoke private eventhandlers?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简短的回答:不。
将事件处理程序声明为公共事件处理程序,或者更好的是,创建一个公共代理方法,例如
直接访问私有成员会破坏将其声明为私有的目的。
Short answer: don't.
Declare your event handler as public or, better yet, create a public proxy method, like
Giving direct access to a private member defeats the purpose of declaring it private.
创建事件处理程序和其他类都可以调用的公共方法。一般来说,直接调用事件处理程序不是一个好主意。仔细考虑您想要做什么,您应该能够找到更符合您想要做的概念的代码结构。您不希望其他班级单击按钮;您希望其他班级执行单击按钮也可以执行的操作。
Create a public method that both the event handler and the other class can call. In general, it's a bad idea to call event handlers directly. Think carefully about what you're trying to do and you should be able to find a code structure that more closely matches the concept of what you're trying to do. You don't want your other class to click a button; you want your other class to do something that clicking a button will also do.
使用私有方法订阅和使用私有订阅者触发事件都没有限制。到目前为止,您有任何错误吗?
there is no restriction on both subscribing with private method and firing event with private subscriber. Did you have any errors so far?