Aar*_*ark 3 c# extension-methods static legacy-code this
我有点困惑,为什么这不会给出错误.我发现这些代码深入到一些过时的遗留软件中,并且很惊讶它看起来有用.
public static string CleanFileName(this string fileName)
{
return CleanFileName(fileName, 64);
}
public static string CleanFileName(this string fileName, int maxLength)
{
//some logic
}
Run Code Online (Sandbox Code Playgroud)
我对扩展方法的体验是这样称呼它:
fileName.CleanFileName(64);
Run Code Online (Sandbox Code Playgroud)
这只能起作用,因为它也是静态方法吗?这是一种常见的做法,只是我还没有看到过的东西,或者是我应该用火杀死的一段过时的遗留代码?
Kir*_*oll 10
可以选择性地调用扩展方法,就好像"this"修饰符甚至不存在一样(也称为常规静态方法).这样做的可读性较差,但语法上有效.
另一个答案是误导,因为"它的工作原理是因为方法调用是在与其重载相同的类型内进行的." 暗示关于扩展方法的一些事 你可以调用扩展方法作为普通的静态方法,而不管你碰巧在哪个类中.但是通过下面的评论,听起来混淆的是这个类是否需要合格.在这种情况下,Nathan是正确的,可以省略类名的原因是因为调用是在与重载相同的类中发生的.
它的工作原理是因为调用CleanFileName(string, int)
是在相同的类型内进行的CleanFileName(string)
,它允许以标准方法语法而不是扩展方法语法进行调用.因此,在扩展方法之前不需要字符串实例前缀.
从语义上讲,static string Foo(this string foo, int bar) { }
可以以Foo(string, int)
或的形式调用string.Foo(int)
.