扩展方法 VS 静态方法解析 - 我在规范中错过了什么?
我添加了一个扩展方法,它是 string.Format 的快捷方式:
public static string Format(this string format, params object[] args)
{
return String.Format(format, args);
}
当我像这样调用此方法时:
"{0}".Format(1);
一切都像魅力一样。 虽然
"{0}".Format("1");
无法编译并显示此错误消息:
错误CS0176:成员 'string.Format(字符串, 参数 object[])' 无法通过 实例参考;限定它与 输入名称代替
我通过重命名方法解决了这个问题(哦,这很痛苦)。但为什么会发生这种情况呢?我知道扩展与实例优先级 - 但这不是实例方法。在我看来,如果无法解析一条路径(在非静态上下文中引用静态方法),则应尝试另一条路径(完全合法)。我在规格中错过了什么?
更新1添加了编译错误消息。
I've added an extension method that is a shortcut to string.Format:
public static string Format(this string format, params object[] args)
{
return String.Format(format, args);
}
When I invoke this method like this:
"{0}".Format(1);
everything works like a charm.
While
"{0}".Format("1");
does not compile with this error message:
error CS0176: Member
'string.Format(string, params
object[])' cannot be accessed with an
instance reference; qualify it with a
type name instead
I fixed this issue by renaming a method (ooh it was a pain). But why does it happen? I know about extension vs instance priority - but this is not an instance method. And IMO if one path could not be resolved (referencing static method in non-static context) then the other (fully legitimate) should be attempted. What do I miss in spec?
Update 1 Added compile error message.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
第 7.5.3.1 节(函数成员适用性)没有提及成员是否是静态的。换句话说,静态方法
String.Format(String, params Object[] args)
在您的第二次调用中仍然适用,即使它实际上不起作用。仅当未找到适用的函数成员时才会搜索扩展方法。
换句话说,成员查找是在类型和一组参数(以及潜在的类型参数)上执行的。成员查找结果的验证稍后完成,作为第 7.6.5.1 节的最后一步。
Section 7.5.3.1 (function member applicability) says nothing about whether a member is static or not. In other words, the static method
String.Format(String, params Object[] args)
is still applicable in your second invocation, even though it won't actually work.Extension methods are only searched for if no applicable function members are found.
In other words, member lookup is performed on a type and a set of arguments (and potentially type arguments). The validation of the result of the member lookup is done later, as the final step of section 7.6.5.1.