开发者

Extension methods in C#: why does this work?

I'm a little confused as to why this doesn't give an error. I found this code deep inside of some outdated legacy software and was surprised to see it work.

public static string CleanFileName(this string fileName)
{
  return CleanFileName(fileName, 64);
}

public static string CleanFileName(this string fileName, int maxLength)
{
  //some logic
}

My experience with extension methods is to call it like th开发者_JS百科is:

fileName.CleanFileName(64);

Does this only work because its a static method as well? Is this common practice and just something I haven't seen yet or a piece of outdated legacy code that I should kill with fire?


Extension methods can always optionally be called as if the "this" modifier was not even there (aka as a normal static method). It's less readable to do this, but syntactically valid.

The other answer is misleading because "It works because the method call is being made from within the same type as its overload." implies something about extension methods. You can invoke extension methods as normal static methods regardless of what class you happen to be in. But through the comments below, it sounds like the confusion is whether the class needs to be qualified or not. And in that vein, Nathan is correct that the reason the class name can be elided is because the call is happening from within the same class as the overload.


It works because the call to CleanFileName(string, int) is being made from within the same type as CleanFileName(string), which allows the call to be made in standard method syntax, rather than extension method syntax. As such, no string instance prefix is required in front of the extension method.

Semantically speaking, static string Foo(this string foo, int bar) { } can be called in the form of Foo(string, int) or string.Foo(int).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜