gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 03:34:45 33 4
gpt4 key购买 nike

我正在查看 new features in 中的几个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' 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 博客的示例不正确吗?为什么这行不通?


博客文章现已更新以反射(reflect)最新更新,但这里有一个屏幕截图以防博客出现故障:

blog

最佳答案

自从撰写这些博文以来,语法似乎略有变化。如错误消息所示,将 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>
}

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

从 C# 7.2 版开始,情况就不应该这样了,也可以使用 const 值,例如 PI

关于c# - 如何使用 C#6 "Using static"功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31852389/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com