委托继承说明
我知道操作只是一个预先声明的委托,它可以接受定义类型的单个参数。所以 Action
表示一个没有返回值并接受单个字符串参数的方法。到目前为止,一切都很好。
在我的代码中,我有这个方法:
public void Send<TMessageType>(Types.MessageBase<TMessageType> message)
{
Console.WriteLine("Message Sent");
List<Delegate> subscriptions;
if (register.TryGetValue(typeof(TMessageType), out subscriptions))
{
foreach (Delegate subscription in subscriptions)
{
Console.WriteLine("Invoking....");
subscription.DynamicInvoke(message);
}
}
}
订阅变量中的所有委托实际上都实例化为操作。我的问题是,为什么我的代码有效?为什么我不需要在使用它之前将我的委托重新转换为操作(它将是 Action
)?当然默认委托类型不知道需要什么参数?
I understand that an action is just a pre-declared delegate that can accept a single parameter of the type defined. so Action<String>
represents a method that has no return and accepts a single string parameter. So far so good.
In my code i have this method:
public void Send<TMessageType>(Types.MessageBase<TMessageType> message)
{
Console.WriteLine("Message Sent");
List<Delegate> subscriptions;
if (register.TryGetValue(typeof(TMessageType), out subscriptions))
{
foreach (Delegate subscription in subscriptions)
{
Console.WriteLine("Invoking....");
subscription.DynamicInvoke(message);
}
}
}
All of the Delegates in the subscriptions variable were actually instantiated as actions. My question is, why does my code work? Why dont i need to cast my delegate back into an action (it would be Action<TMessageType>
), before i can use it? surely the default delegate type has no idea what parameters to expect?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
简而言之,因为您对 DynamicInvoke 的调用是后期绑定调用,并且实际上并不知道它是否需要参数。
MSDN
附注:
鉴于您了解传递给
Action
的类型,您可能应该重构代码以直接调用操作,而不是使用DynamicInvoke
(如果您可以避免使用它),否则会出现这种情况会影响性能。如果由于未显示的限制而无法避免它,那就这样吧。当然,我不知道重构
TryGetValue
调用会涉及什么。Well the short answer is because your call to
DynamicInvoke
is a late-bound call and doesn't actually know whether or not it even needs parameters.MSDN
As a side note:
Given that you have knowledge of the type being passed to the
Action
you should probably refactor your code to directly invoke the actions and not useDynamicInvoke
if you can avoid it as there will be a performance impact. If you cannot avoid it due to restrictions not shown then so be it.Of course I don't know what would be involved in refactoring the
TryGetValue
call.不,它不知道也不关心 - 它需要一堆“对象”参数并用它来调用你的操作。它不会在编译时检查,而是在运行时检查 - 请参阅此处了解详细信息< /a>
no it does not know and doesn't care - it takes a bunch of "object"-parameters and calls your action with it. It is not checked at compiletime but at runtime - see here for details
您正在使用
DynamicInvoke
,顾名思义,它动态调用委托。它比 Invoke 慢一个数量级,但能够在运行时自动匹配参数类型,而不是依赖编译时信息。You're using
DynamicInvoke
, which, as its name implies, invokes dynamically the delegate. It's an order of magnitude slower thenInvoke
but is able to match automatically the parameter type, at runtime rather than relying on compile time information.