首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用C#6“Using static”功能?

如何使用C#6“Using static”功能?
EN

Stack Overflow用户
提问于 2018-04-13 01:34:29
回答 1查看 0关注 0票数 0

我正在看看C#6 中的一些新功能,特别是 “使用静态”

using static is a new kind of using clause that lets you import static members of types directly into scope.

想法如下:

代码语言:javascript
复制
using System;

class Program 
{ 
    static void Main() 
    { 
        Console.WriteLine("Hello world!"); 
        Console.WriteLine("Another message"); 
    } 
}

可以Console使用静态类的新C#6功能来省略重复的语句:

代码语言:javascript
复制
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”

为什么这不起作用?

EN

回答 1

Stack Overflow用户

发布于 2018-04-13 11:12:01

如错误消息所示,添加static你的包括声明:

代码语言:txt
复制
using static System.Console;
//      ^
class Program 
{ 
    static void Main() 
    { 
        WriteLine("Hello world!"); 
        WriteLine("Another message"); 
    } 
}

然后,你的代码将编译。


请注意,这只适用于声明为static

例如,考虑System.Math

代码语言:txt
复制
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;

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100008092

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档