如何使用 C#6 "Using static" 功能?

How do I use the C#6 "Using static" feature?

我正在看一些 new features in C# 6,具体来说, "using static".

using static is a new kind of using clause that lets you import static members of types directly into scope.
(Bottom of the blog post)

思路如下,根据我找的几个教程,
而不是:

using System;

class Program 
{ 
    static void Main() 
    { 
        Console.WriteLine("Hello world!"); 
        Console.WriteLine("Another message"); 
    } 
}

您可以省略重复的 Console 语句,使用新的 C# 6 特性使用静态 类:

using System.Console;
//           ^ `.Console` added.
class Program 
{ 
    static void Main() 
    { 
        WriteLine("Hello world!"); 
        WriteLine("Another message"); 
    } // ^ `Console.` removed.
}

但是,这似乎对我不起作用。我在 using 语句中收到错误消息:

"A 'using namespace' directive can only be applied to namespaces; 'Console' is a type not a namespace. Consider a 'using static' directive instead"

我使用的是 visual studio 2015,构建语言版本设置为 "C# 6.0"

什么给了? msdn 博客的示例不正确吗?为什么这不起作用?


博客 post 现已更新以反映最新更新,但这里有一个屏幕截图以防博客出现故障:

自从撰写这些博文以来,语法似乎略有变化。如错误消息所示,将 static 添加到您的 include 语句中:

using static System.Console;
//      ^
class Program 
{ 
    static void Main() 
    { 
        WriteLine("Hello world!"); 
        WriteLine("Another message"); 
    } 
}

然后,您的代码将编译。


请注意,在 C# 6.0 中,这仅适用于声明为 static 的成员。

例如,考虑 System.Math

public static class Math {
    public const double PI = 3.1415926535897931;
    public static double Abs(double value);
    // <more stuff>
}

using static System.Math时,你可以直接使用Abs();
但是,您仍然需要添加前缀 PI 因为它不是静态成员:Math.PI;.

从 C# 7.2 版开始,情况不应该是这样,constPI 也可以使用。

using 语句中的 static 关键字将只导入一个指定类型(及其嵌套类型)。此外,您不得再提供类型名称。因此,只需将静态添加到您的使用中即可。

注意:只有当两个类在逻辑上密切相关时才使用此功能,否则会使阅读代码变得非常困难。