从子类调用方法
在 Silverlight / C# 中,我有 Main 类,它创建 Child 的实例,Child _child = new Child(...)
现在,在 Child 类中我需要从 Main 类调用一个方法。最好的方法应该是什么?活动?
In Silverlight / C#, I have class Main, which creates an instance of Child, Child _child = new Child(...)
Now, in Child class I need to call a method from Main class. What should be the best way to do this ? Events?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
最简单的解决方案是为
Child
类的实例提供对Main
的引用:这可以通过抽象出
Main
后面的类来进一步改进。IMain
接口,以最大限度地减少耦合。但最好的解决方案是利用事件冒泡
Simplest solution will be to provide a reference to
Main
to an instance ofChild
class:This can be further improved by abstracting away
Main
class behind aIMain
interface in order to minimize coupling.But best solution will be to utilize event bubbling
答案取决于调用的语义是什么;你的例子很模糊,没有明显的语义可以推理,所以不可能给出一个好的答案。
Main 是否为 Child 提供服务?例如,Child 想要在 Main 上执行的调用是否类似于“获取有权执行 blah 操作的用户列表”或“将 11 月份的所有应收账款相加”之类的内容?
或者 Main 对与 Child 相关的事件做出反应?例如,也许 Child 是一个按钮,Main 是一个表单,Main 希望在单击按钮时做出反应。
在前一种情况下,Main 应该向 Child 提供一个对象(可能是它本身)来实现所需的服务。该对象可能是 Main 本身,或者是方法或接口的委托,但它是 Child 在需要服务时可以调用的东西。
在后一种情况下,Main 应该监听 Child 引发的事件。
哪个是正确的取决于对象的含义;你能更清楚地描述一下意思吗?
The answer depends upon what the semantics of the call are; your example is vague and has no obvious semantics to reason from, so it is impossible to give a good answer.
Is Main providing a service to Child? For example, is the call that Child wants to do on Main something like "get me the list of users who are authorized to do blah", or "add up all the accounts receivable for November"?
Or is Main reacting to an event assocaited with Child? For example, perhaps Child is a button and Main is a form, and Main wishes to react when the button is clicked.
In the former case, Main should provide an object -- possibly itself -- to Child that implements the desired service. The object might be Main itself, or a delegate to a method, or an interface, but it's something that Child can invoke when the service is needed.
In the latter case, Main should listen to the event raised by Child.
Which is correct depends on the meaning of the objects; can you describe the meaning more clearly?
三项赛是正确的模式。有关对象中信息流的概念原因,请参阅此答案/类层次结构。
Eventing is the proper pattern. See this answer on the conceptual reasons around information flow in an object/class hierarchy.