我已经阅读了开源的C#代码,其中有很多对我而言奇怪的语法。
他们使用this关键字来声明方法参数,像这样:
this object @object
这是什么意思?
如果我删除数据类型前面的'this'关键字,那么它会以不同的方式工作吗?
听起来像是一个扩展方法。
@
符号允许变量名称与C#关键字相同 - 我个人倾向于避开它们。
如果移除this
关键字,它将不再是扩展方法,而仅仅是一个静态方法。根据调用代码的语法,它可能无法编译,例如:
public static class IntegerMethods
{
public static int Add(this int i, int value)
{
return i + value;
}
}
int i = 0;
// This is an "extension method" call, and will only compile against extension methods.
i = i.Add(2);
// This is a standard static method call.
i = IntegerMethods.Add(i, 2);
编译器会将所有“扩展方法调用”转换为标准静态方法调用,但是扩展方法调用仍然只能针对有效的扩展方法按照“此类型名称”语法进行操作。this
参数命名为@this
。虽然我得出的结论是这样做“太可爱了”。 - Matthew Watsonthis
参数称为self
。有效。 - Daren Thomas“此类型名称”语法用于扩展方法。
例如,如果我想要为字符串添加一个UnCamelCase
方法 (这样我就可以使用"HelloWorld".UnCamelCase()
来产生 "Hello World") - 我会写下这个:
public static string UnCamelCase(this string text)
{
/*match any instances of a lower case character followed by an upper case
* one, and replace them with the same characters with a space between them*/
return Regex.Replace(text, "([a-z])([A-Z])", "$1 $2");
}
this string text
表示你正在处理的具体字符串实例,而 text 是它的标识符。
@ 语法允许使用通常被保留的变量名。