Cer*_*rus 113 c# static using c#-6.0 visual-studio-2015
using static是一种新的using子句,它允许您将类型的静态成员直接导入范围.
(博客文章的底部)
根据我发现的几个教程,这个想法如下,
而不是:
using System;
class Program
{
static void Main()
{
Console.WriteLine("Hello world!");
Console.WriteLine("Another message");
}
}
Run Code Online (Sandbox Code Playgroud)
您可以Console
使用使用静态类的新C#6功能省略重复的语句:
using System.Console;
// ^ `.Console` added.
class Program
{
static void Main()
{
WriteLine("Hello world!");
WriteLine("Another message");
} // ^ `Console.` removed.
}
Run Code Online (Sandbox Code Playgroud)
但是,这似乎对我没有用.我在using
声明中收到错误,说:
"A'
using namespace
'指令只能应用于名称空间;'Console
'是一种类型而不是名称空间.请考虑使用'using static
'指令"
我正在使用visual studio 2015,我将构建语言版本设置为"C#6.0"
是什么赋予了?msdn博客的例子不正确吗?为什么这不起作用?
该博客文章现已更新,以反映最新的更新,但这是一个截图,以防博客发生故障:
Cer*_*rus 165
自从撰写这些博客文章以来,语法似乎略有变化.如错误消息所示,添加static
到include语句:
using static System.Console;
// ^
class Program
{
static void Main()
{
WriteLine("Hello world!");
WriteLine("Another message");
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您的代码将编译.
请注意,在C#6.0中,这仅适用于声明为的成员static
.
例如,考虑System.Math
:
public static class Math {
public const double PI = 3.1415926535897931;
public static double Abs(double value);
// <more stuff>
}
Run Code Online (Sandbox Code Playgroud)
什么时候using static System.Math
,你可以使用Abs();
.
但是,你仍然需要加前缀,PI
因为它不是静态成员:Math.PI;
.
在C#7.2(可能更低)中,情况不应该是这样,也可以使用const
像这样的值PI
.