What does “this” mean in a static method declaration?

China☆狼群 提交于 2020-01-11 08:42:08

问题


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)

What does the word this mean in that context?


回答1:


It means SomeMethod() is an extension method to the Object class.

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.

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);



回答2:


It is how you declare an extension method.

This means that you can invoke SomeMethod with .SomeMethod for any object. The object before the . will be the blah parameter.

string s = "sdfsd";
Object result = s.SomeMethod(false);

The extension method will be available on all types inheriting from the type of the this parameter, in this case object. If you have SomeMethod(this IEnumerable<T> enumerable) it will be available on all IEnumerable<T>:s like List<T>.




回答3:


Extension method:

http://msdn.microsoft.com/en-us/library/bb383977.aspx



来源:https://stackoverflow.com/questions/5075988/what-does-this-mean-in-a-static-method-declaration

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!