理论:委托传递给构造函数
所以我想知道这样的事情是否可能:
我是一个程序,我即将创建我的一个对象的实例。我触发一个事件,让所有订阅者知道我即将创建一个对象。作为此事件的一部分,我传递一个哈希表,稍后将其传递给对象的构造函数。
然后订阅者就可以修改这个哈希表了,是吗?他们可以添加委托类型的条目并将该类型的委托作为值吗?一旦订阅者完成其业务,预创建事件就结束。对哈希表所做的更改是否会在触发事件的对象中表示?那么,如果这个哈希表被传递给一个对象的构造函数,那么该对象可能包含来自外部源的方法吗?
所以本质上 -
去创建对象
火灾请求委托事件
在对象的构造函数中使用由事件修改的委托哈希表
如果存在相同类型的委托,则对象使用哈希表中的方法代替自己的方法
现在对象在标准函数上运行自定义代码
同样,我真的不知道我所说的是否可能或有意义。
So I was wondering if something like this is possible:
I am a program, I am about to create an instance of one of my objects. I fire an event letting any subscribers know that I am about to create an object. As a part of this event I pass through a Hashtable that I will later pass to the constructor of my object.
Subscribers would then be able to modify this Hashtable yes? They could add entries for a delegate type with a delegate of that type as the value? Once the subscriber finishes doing their business, the pre-create event finishes. Would the changes made to the Hashtable be represented in the object that fired the event? So then if this Hashtable was passed to the constructor of an object, that object could potentially contain methods from an outside source?
So essentially -
Go to create object
Fire request delegate event
Use delegate hashtable modified by event in constructor of object
Object uses methods from hashtable in place of own if exists delegate of same type
Now object runs custom code on standard functions
Again, I really don't know if what I'm saying is even possible, or makes sense.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是可能的,但我建议不要公开发送
HashSet
。原因是任何订阅者都可以修改HashSet
中的值。相反,我不知道事件是这里的正确行动方针。我仍然会使用委托,但我不会将它们公开为事件。发布/订阅模式在这里可能更好(其中想要通知的对象将通过 Sub/Unsub 方法传递委托)。
这允许您修改委托签名,以便实现在您进行调用时将数据值返回给您(而不是传递
HashSet
)。然后,您不只是进行一次调用,而是调用
GetIncationList
获取每个单独的委托。然后,您将循环并收集返回的值。从那时起,您将适当地聚合这些值,然后将该聚合传递给对象的构造函数。
It's possible, but I would recommend against sending a
HashSet<T>
openly. The reason being that any subscriber could modify the values in theHashSet<T>
.Instead, I don't know that an event is the right course of action here. I would still use delegates, but I would not expose them as events. A pub/sub pattern might be better here (where an object that wants to be notified would pass the delegate through Sub/Unsub methods).
This allows you to modify the delegate signature so that the implementation will return the data values to you when you make the call (instead of passing around the
HashSet<T>
).Then, instead of just making one call, you would call
GetInvocationList
to get each individual delegate. You would then loop through and collect the values that are returned.From that point, you would aggregate the values appropriately and then pass that aggregate to the constructor of your objects.