什么"这"意思是在静态方法声明? [英] What does "this" mean in a static method declaration?
问题描述
我已经看到了使用关键字这
在函数的参数声明部分code。例如:
I've seen some code that uses the keyword this
in the function parameter declaration. For example:
public static Object SomeMethod( this Object blah, bool blahblah)
这个词是什么这
意味着在这方面?
推荐答案
这意味着的someMethod()
是的扩展方法到对象
类。
定义后,你可以调用任何对象这个方法
情况下(尽管它被宣布静态
)一样,因此:
After defining it you can call this method on any Object
instances (despite it being declared static
), like so:
object o = new Object();
bool someBool = true;
// Some other code...
object p = o.SomeMethod(someBool);
在这个对象
参数是指你在调用它的对象,实际上不是在参数表中找到。
The this Object
parameter refers to the object you call it on, and is not actually found in the parameter list.
为什么它宣布其原因静态
,而你把它像一个实例方法是因为编译器是在IL一个真正的静态调用。那深藏下来了,所以我就不细说了,但同时也意味着你可以调用它,就好像它是任何静态方法:
The reason why it's declared static
while you call it like an instance method is because the compiler translates that to a real static call in the IL. That goes deep down though, so I shan't elaborate, but it also means you can call it as if it were any static method:
object o = new Object();
bool someBool = true;
// ...
object p = ObjectExtensions.SomeMethod(o, someBool);
这篇关于什么"这"意思是在静态方法声明?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!