我正在看看C#6 中的一些新功能,特别是 “使用静态”。
using static is a new kind of using clause that lets you import static members of types directly into scope.
想法如下:
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”
为什么这不起作用?
发布于 2018-04-13 11:12:01
如错误消息所示,添加static
你的包括声明:
using static System.Console;
// ^
class Program
{
static void Main()
{
WriteLine("Hello world!");
WriteLine("Another message");
}
}
然后,你的代码将编译。
请注意,这只适用于声明为static
。
例如,考虑System.Math
:
public static class Math {
public const double PI = 3.1415926535897931;
public static double Abs(double value);
// <more stuff>
}
使用 static System.Math
时,你可以用Abs();
。
但是,你仍然需要在PI
因为它不是静态成员:Math.PI;
。
https://stackoverflow.com/questions/-100008092
复制相似问题