在静态类的静态方法的参数中使用此参数? [英] Using this in parameters of static methods in static class?
问题描述
为什么我应该在静态类的静态函数中对参数对象使用'this'?我的意思是使用这两种方法的真正区别是什么?
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)
}
推荐答案
public static string AsJson(this object obj)
它是 扩展方法 在 object
扩展方法被定义为静态方法,但由调用使用实例方法语法.他们的第一个参数指定了键入要对其进行操作的方法,并且参数之前是此修饰符.
您的其他方法只是一个简单的静态方法.
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
但是,编译器生成的中间语言(IL)将您的代码转换为对静态方法的调用.
However, the intermediate language (IL) generated by the compiler translates your code into a call on the static method.
所以
string str = obj.AsJson();
翻译成
string str = Extensions.AsJson(obj);
这就是为什么您可以这样做:
That is why you can actually do:
object obj = null;
obj.AsJosn(); //Would not result in NRE
这篇关于在静态类的静态方法的参数中使用此参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!