选择看起来像错误/缺失功能的重载时,奇怪的C#编译器行为
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了选择看起来像错误/缺失功能的重载时,奇怪的C#编译器行为,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2043字,纯文字阅读大概需要3分钟。
内容图文
![选择看起来像错误/缺失功能的重载时,奇怪的C#编译器行为](/upload/InfoBanner/zyjiaocheng/811/e1906622fb8646808a555499aa9b77c7.jpg)
我最近发现了一个有趣的C#编译器行为.想象一下这样的界面:
public interface ILogger
{
void Info(string operation, string details = null);
void Info(string operation, object details = null);
}
如果我们这样做
logger.Info("Create")
编译器会抱怨他不知道选择哪个重载(不明确的调用……).似乎合乎逻辑,但是当你尝试这样做时:
logger.Info("Create", null)
它突然没有麻烦,搞清楚null是一个字符串.此外,似乎找到正确的重载的行为已经随着时间的推移而改变,我发现旧代码中的错误在之前工作并且停止工作,因为编译器决定使用另一个重载.
所以我真的很想知道为什么C#在第二种情况下不会像第一种情况那样产生相同的错误.这样做似乎非常符合逻辑,但它尝试将其解析为随机重载.
附:我不认为提供这种模糊的界面是好的,不建议这样做,但遗产是遗留的,必须保持:)
解决方法:
在C#6中引入了一个突破性的变化,使得重载分辨率更好. Here it is与功能列表:
Improved overload resolution
There are a number of small improvements to overload resolution, which will likely result in more things just working the way you’d expect them to. The improvements all relate to “betterness” – the way the compiler decides which of two overloads is better for a given argument.
One place where you might notice this (or rather stop noticing a problem!) is when choosing between overloads taking nullable value types. Another is when passing method groups (as opposed to lambdas) to overloads expecting delegates. The details aren’t worth expanding on here – just wanted to let you know!
but instead it tries and resolves it to random overload.
不,C#不会随机选择重载,这种情况是模糊的调用错误. C#选择更好的方法.请参阅C#规范中的7.5.3.2更好的函数成员一节:
7.5.3.2 Better function member
Otherwise, if MP has more specific parameter types than MQ, then MP is better than MQ. Let {R1, R2, …, RN} and {S1, S2, …, SN} represent the uninstantiated and unexpanded parameter types of MP and MQ. MP’s parameter types are more specific than MQ’s if, for each parameter, RX is not less specific than SX, and, for at least one parameter, RX is more specific than SX:
鉴于字符串比对象更具体,并且在null和string之间存在隐式转换,那么神秘就解决了.
内容总结
以上是互联网集市为您收集整理的选择看起来像错误/缺失功能的重载时,奇怪的C#编译器行为全部内容,希望文章能够帮你解决选择看起来像错误/缺失功能的重载时,奇怪的C#编译器行为所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。