我如何使用 C#6“使用静态"?特征? [英] How do I use the C#6 "Using static" feature?

查看:16
本文介绍了我如何使用 C#6“使用静态"?特征?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在查看几个

解决方案

自这些博客文章撰写以来,语法似乎略有变化.正如错误消息所暗示的那样,将 static 添加到您的包含语句中:

使用静态 System.Console;//^课程计划{静态无效主(){WriteLine("你好世界!");WriteLine("另一条消息");}}

然后,您的代码将被编译.

<小时>

请注意,在 C# 6.0 中,这仅适用于声明为 static 的成员.

例如,考虑System.Math:

public static class Math {公共常量双 PI = 3.1415926535897931;公共静态双绝对(双值);//<更多的东西>}

使用静态System.Math时,你可以只使用Abs();.
但是,您仍然必须在 PI 前面加上前缀,因为它不是静态成员:Math.PI;.

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

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:

解决方案

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.

这篇关于我如何使用 C#6“使用静态"?特征?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆