【问题标题】:"using static" throwing error [closed]“使用静态”抛出错误[关闭]
【发布时间】:2017-11-16 01:23:32
【问题描述】:

我尝试使用using static System.Console; 而不是using System;,所以我只需要输入WriteLine("bla")Console.WriteLine("bla")

我的代码如下:

using static System.Console;

public class Program
{
    public static void Main()
    {
        WriteLine("this is text")
    }
}

它会抛出以下错误:

  • 编译错误(第 1 行,第 7 列):需要标识符; 'static' 是关键字

  • 编译错误(第 1 行,第 14 列):预期的类、委托、枚举、接口或结构

但是,当我使用using System;Console.WriteLine("this is text") 时,它可以完美运行。

如果有人能解释我的代码有什么问题,那就太好了,但请彻底解释,因为我对编程知之甚少:S

【问题讨论】:

  • 您不必声明它staticConsole 已经是Static 类,这就是为什么您可以使用. 运算符直接访问方法而无需将该类作为对象。只需从 import 语句中删除 static
  • @CoderofCode:OP 正在讨论 C# 6 中的新 using static 功能。假设正在使用最新的编译器,它应该可以工作。
  • 致 OP:您使用的是什么版本的编译器? IE。你真的在使用 C# 6 吗?
  • 请包括Visual Studio的版本、编译器和任何其他相关细节。
  • 这些是我在使用 C# 5 编译器时遇到的确切错误。

标签: c# using c#-6.0 using-statement using-directives


【解决方案1】:

在 C# 7.0 / VS2017 中,代码应该可以工作,除了第 7 行的错误 - 它缺少终止分号。

以下代码编译运行,并显示:

这是文字

using static System.Console;

public class Program
{
    public static void Main()
    {
        WriteLine("this is text");
    }
}

【讨论】:

  • 是的,忘记了帖子中的分号,但它在实际代码中。我猜.NET Fiddle 没有使用最新的 C# 编译器。在 Visual Studio 中,代码运行良好。谢谢!
猜你喜欢
  • 2015-12-01
  • 2018-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-02-21
  • 2012-03-22
相关资源
最近更新 更多