简体   繁体   English

扩展方法VS静态方法解析-我在规范中会错过什么?

[英]Extension-methods VS static method resolution - what do I miss in spec?

I've added an extension method that is a shortcut to string.Format: 我添加了一个扩展方法,它是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; 错误CS0176:无法使用实例引用访问成员'string.Format(string,params object [])'; 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. 我知道扩展vs实例优先级-但这不是实例方法。 And IMO if one path could not be resolved (referencing static method in non-static context) then the other (fully legitimate) should be attempted. 而IMO如果无法解析一个路径(在非静态上下文中引用静态方法),则应尝试另一路径(完全合法)。 What do I miss in spec? 我在规格上想念什么?

Update 1 Added compile error message. 更新1添加了编译错误消息。

Section 7.5.3.1 (function member applicability) says nothing about whether a member is static or not. 7.5.3.1节(函数成员的适用性)未提及成员是否静态。 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. 换句话说,静态方法String.Format(String, params Object[] args)仍然适用于您的第二次调用,即使它实际上不起作用。

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. 稍后将进行成员查找结果的验证 ,这是第7.6.5.1节的最后一步。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM