Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

c# - How do I use the C#6 "Using static" feature?

I'm having a look at a couple of the new features in C# 6, specifically, "using static".

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)

The idea is as follows, according to a couple of tutorials I found,
Instead of:

using System;

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

You can omit the repeated Console statement, using the new C# 6 feature of using static classes:

using System.Console;
//           ^ `.Console` added.
class Program 
{ 
    static void Main() 
    { 
        WriteLine("Hello world!"); 
        WriteLine("Another message"); 
    } // ^ `Console.` removed.
}

However, this doesn't appear to be working for me. I'm getting an error on the using statement, saying:

"A 'using namespace' directive can only be applied to namespaces; 'Console' is a type not a namespace. Consider a 'using static' directive instead"

I'm using visual studio 2015, and I have the build language version set to "C# 6.0"

What gives? Is the msdn blog's example incorrect? Why doesn't this work?


The blog post has now been updated to reflect the latest updates, but here's a screenshot in case the blog goes down:

blog

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It appears the syntax has slightly changed since those blog posts were written. As the error message suggests, add static to your include statement:

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

Then, your code will compile.


Note that, in C# 6.0, this will only work for members declared as static.

For example, consider 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, you can just use Abs();.
However, you'd still have to prefix PI because it isn't a static member: Math.PI;.

Starting with C# version 7.2, this shouldn't be the case, const values like PI can be used as well.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...