C# 编译器功能还是我疯了?
在重写事件调用函数以一般地处理事件及其参数之后,我开始检查我的代码(以匹配更改),并且我注意到编译器隐式进行了通用调用。
这是我的函数:
private void InvokeEvent<TArgs>(EventHandler<TArgs> invokedevent, TArgs args)
where TArgs : EventArgs
{
EventHandler<TArgs> temp = invokedevent;
if (temp != null)
{
temp(this, args);
}
}
这是调用该函数的行:
InvokeEvent(AfterInteraction, result);
编译没有问题,智能感知甚至显示“正确”的调用(带有该部分)。
这是编译器功能(实际上可以从第二个参数直接推断出泛型类型),还是我会因为什么而疯狂而错过重点?
After rewriting my event invocation function to handle the events and their arguments generically, I started going over my code (to match the change), and I noticed that the compiler implicitly made the generic call.
Here's my function:
private void InvokeEvent<TArgs>(EventHandler<TArgs> invokedevent, TArgs args)
where TArgs : EventArgs
{
EventHandler<TArgs> temp = invokedevent;
if (temp != null)
{
temp(this, args);
}
}
and here is the line to call the function:
InvokeEvent(AfterInteraction, result);
This compiles without a problem, and the intellisense even display the "correct" call (with the part).
Is this a compiler feature (the generic type can, actually, be directly inferred from the second argument), or am I going crazy over nothing and missing the point?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果编译器可以推断所有类型参数,那么您不需要显式指定它们。在这种情况下,它可以从第二个参数推断出 TArgs。
但是,如果它无法推断出所有类型参数,则需要指定所有类型参数,甚至是编译器可以推断出的参数。
If the compiler can infer all type parameters then you don't need to specify them explicitly. In this case it can infer
TArgs
from the second parameter.But if it can't infer all type parameters, you need to specify all of them, even the ones the compiler could infer.
这是调用类型推断,请阅读此处,搜索章节《类型推断》
It is call type inference, read about it here, search for the chapter "Type Inference"
正如您所说,编译器已从第二个参数推断出类型。
As you have said the compiler has inferred type from the second argument.