简体   繁体   English

扩展方法中的C#静态类访问

[英]c# static class access in extension methods

Whats the difference between matrix.Extension() and ExtensionMethods.Extension(matrix) ?? matrix.Extension()和ExtensionMethods.Extension(matrix)之间有什么区别?

static void Main(string[] args)
{
    decimal[,] testData = new[,] {{1m, 2m}, {3m, 4m}};
    ImmutableMatice matrix = new ImmutableMatice(testData);
    Console.WriteLine(matrix.Extension());  
    Console.WriteLine(ExtensionMethods.Extension(matrix)); // return the same like matrix.Extension() but whats the difference?
}

Extension class 扩展类

static class ExtensionMethods
{
    public static string Extension(this ImmutableMatice array)
    {
       Console.WriteLine("Values of array are: ");
       for (int i = 0; i < array.Array.GetLength(0); i++)
       {
           for (int j = 0; j < array.Array.GetLength(1); j++)
           {
               Console.Write(string.Format("{0} ", array[i, j]));
           }
           Console.Write(Environment.NewLine + Environment.NewLine);
       }
    return null;
}

Whats the difference between matrix.Extension() and ExtensionMethods.Extension(matrix)? matrix.Extension()和ExtensionMethods.Extension(matrix)之间有什么区别?

Nothing whatsoever. 没事 The compiler translates the first into the second, effectively. 编译器有效地将第一个转换为第二个。

There will be a difference in C# 6, where if you've statically imported the ExtensionMethods type specifically, the first will work and the second won't. C#6 有所不同,如果您专门静态导入了ExtensionMethods类型,则第一个将起作用而第二个将不起作用。 From the "Upcoming features in C#" doc: 从“ C#的即将推出的功能”文档中:

Extension methods are static methods, but are intended to be used as instance methods. 扩展方法是静态方法,但旨在用作实例方法。 Instead of bringing extension methods into the global scope, the using static feature makes the extension methods of the type available as extension methods 使用静态功能不会将扩展方法引入全局范围,而是将类型的扩展方法用作扩展方法

(This hasn't been implemented in the current CTP though.) (不过,当前的CTP中尚未实现此功能。)

Given that they're equivalent, you may be asking yourself why this syntactic sugar exists at all. 鉴于它们是等效的,您可能会问自己为什么这种语法糖根本不存在。 There are two reasons: 有两个原因:

  • It makes it far more convenient to chain method calls together, if some of them happen to be static. 如果某些方法调用是静态的,则使将方法调用链接在一起更加方便。 For example: 例如:

     foo.Bar().Baz().Qux() 

    is simpler to read than: 比以下内容更容易阅读:

     ThirdClass.Qux(SecondClass.Baz(FirstClass.Bar(foo))) 
  • It allows for the LINQ pattern to work consistently across interfaces and types, whether the types implement the pattern directly as instance members, or whether extension methods are used. 它允许LINQ模式在接口和类型之间一致地工作,无论这些类型是直接作为实例成员实现该模式,还是是否使用扩展方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM