我正在看其中的几个新功能在C# 6,具体来说,“使用静态”.
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
' 指令只能应用于命名空间; 'Console
' 是类型而不是命名空间。考虑一个'using static
' 指令代替”
我使用的是 Visual Studio 2015,并且我将构建语言版本设置为"C# 6.0"
是什么赋予了? msdn博客的例子不正确吗?为什么这不起作用?
该博客文章现已更新以反映最新更新,但这里有一个屏幕截图,以防博客出现故障:
自这些博客文章撰写以来,语法似乎略有变化。根据错误消息提示,添加static
到您的包含声明:
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>
}
When using static System.Math
,你可以只使用Abs();
.
但是,您仍然需要添加前缀PI
因为它不是静态成员:Math.PI;
.
从 C# 版本 7.2 开始,情况不应如此,const
价值观像PI
也可以使用。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)