微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

方法组(C#深入) – 需要帮助更好地了解方法组的内容

所以我已经阅读了一些StackOverflow问题与“什么是一个方法组”以及其他互联网文章有关,他们都说同样的事情在底线 – 方法组是“一组重载的方法”.

然而,阅读Jon Skeet的“C#深度(第二版)”,他在Lambda表达式的上下文中陈述了关于方法组的以下说明(第9.4.1节)

Reasons for change: streamlining generic method calls

Type inference occurs in a few situations. We’ve already seen it apply to implicitly
typed arrays,and it’s also required when you try to implicitly convert a method group
to a delegate type. This can be particularly confusing when the conversion occurs
when you’re using a method group as an argument to another method: with overloading
of the method being called,and overloading of methods within the method
group,and the possibility of generic methods getting involved,the set of potential
conversions may be enormous.”

任何一个方法组都不仅仅是一组重载的方法,或者他说你可以创建一个保留整个方法组的委托.或者完全不一样,我不太在意.

有人可以解释他在说什么吗?

谢谢,

解决方法

Jon描述的场景是这样的:
int M() {...}
string M<T>(T t) {...}
double M<T>(List<T> t) {...} 
static void M(double d) {...}
... etc ...

void N(Func<int> f) {...}
void N<T>(Action<T> a) {...}
void N<T>(Func<IEnumerable<T>> f) {...}
... etc ...

N(M);

N和M都是方法组,包含可能的数十种方法,有些可能是通用的.向编译器提出的问题是“确定哪些方法N和M是开发人员打算的方法,并且如果预期方法是通用的,则计算出类型参数”.

为了工作,编译器必须尝试每一个可能的N,然后找出哪一个可能的M与N的重载的形式参数的委托类型兼容.它必须丢弃那些不工作的,然后从所有那些潜在的成百上千的组合,找出哪一个是“最好的”,如果有的话.这在语义分析中是一个棘手的问题.

原文地址:https://www.jb51.cc/csharp/95898.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐