扩展方法和静态方法混淆 [英] Extension Method and Static Method Confusing
本文介绍了扩展方法和静态方法混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么我们不用静态方法创建静态类,然后调用该方法传入这样的参数:
Why don't we create a static class with a static method and then call that method to pass in a argument like this :
public static class A{
public static void ToUpperString(string param)
{
param.ToUpper();
}
}
而不是创建扩展方法
instead of creating an Extension Method
public static class A{
public static void ToUpperString(this string param)
{
param.ToUpper();
}
}
这些方法电话有什么区别:
What is the difference between these method call :
string myString = "HelloFromVietnam";
string result1 = A.ToUpperString(mystring);
string result2 = mystring.ToUpperString();
======================= ===
这个问题让我很兴奋。但我还是没想出来。等待你的帮助。 :)
==========================
This question makes me so excited. But I still have not figured it out. Waiting for your helps. :)
推荐答案
因为扩展方法允许您通过添加看起来像是原始类的一部分的方法来扩展密封类。
这使得它们在您的代码中使用时更具可读性:正如您在示例中所示。
除了......您的示例不起作用,并且不会做任何事情,甚至编译!您的意思可能是:
Because Extension methods allow you to "extend" a sealed class by adding methods that look like they are part of the original class.
That makes them more readable when you use them in your code: as you show in your example.
Except...your example wouldn't work, and wouldn't do anything, or even compile! What you meant to say was probably:
public static string ToUpperString(string param)
{
return param.ToUpper();
}
和
And
public static string ToUpperString(this string param)
{
return param.ToUpper();
}
这篇关于扩展方法和静态方法混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文