Using this in parameters of static methods in static class?

眉间皱痕 提交于 2019-12-25 02:29:13

问题


Why should I use 'this' in static functions of static classes to objects in parameter? I mean is the real difference between using those 2 methods?

public static class Extensions
{
    public static string AsJson(this object obj)
    public static string AsJson2(object obj)
}

回答1:


public static string AsJson(this object obj)

Its is an Extension Method on type object

Extension methods are defined as static methods but are called by using instance method syntax. Their first parameter specifies which type the method operates on, and the parameter is preceded by the this modifier.

Your other method is just a simple static method.

public static string AsJson2(object obj)

Both of their calls would be like:

Object obj = new object();
string str = obj.AsJson(); //extension method called

string str2  = Extensions.AsJson2(obj); //Normal static method called

string str3 = Extensions.AsJson(obj); //extension method called like a normal static method

Extension methods are called like instance method but the compiler actually translates into a call to Static method

However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method.

So

string str = obj.AsJson(); 

Translates into

string str = Extensions.AsJson(obj);

That is why you can actually do:

object obj = null;
obj.AsJosn(); //Would not result in NRE



回答2:


The first one is an extension method, whereas the second one is just a static method.

The difference is in how you can call them:

object myObj = new object();
var result = myObj.AsJson();

var result2 = Extensions.AsJson2(myobj);

Note that you can also use the first one as a simple static method:

var result3 = Extensions.AsJson(myObj);

Essentially, it's just syntactical sugar. Upon compilation, the first statement will be transformed into the last one.




回答3:


Using this on a parameter in your method makes it an Extension Method. It means you can do this:

myObj.AsJson();

instead of this:

Extensions.AsJson(myObj);

Rules:

  • Extension methods must be declared as static methods in a static class
  • The this modifier must be on the first parameter of the method


来源:https://stackoverflow.com/questions/21338785/using-this-in-parameters-of-static-methods-in-static-class

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