如何在不调用类的情况下从类调用变量 - c#?

The*_*ato 0 c# class

我想使用这个类中的const变量:

 class foo
 {
    public const bool x = true;
 }
Run Code Online (Sandbox Code Playgroud)

有没有办法在不做foo.x的情况下使用x?

我想像这样使用它:

if( x ) 
Run Code Online (Sandbox Code Playgroud)

而不是这样的:

if( foo.x )
Run Code Online (Sandbox Code Playgroud)

Mar*_*zek 10

要实现这一目标的唯一方法是,以纪念foo静态和使用using static要具有访问foo.xx.

namespace Foo
{
    static class Bar
    {
         public const bool x = true;
    }
}
Run Code Online (Sandbox Code Playgroud)

然后:

using static Foo.Bar;
Console.WriteLine(x);
Run Code Online (Sandbox Code Playgroud)

using static 是一个C#功能,所以请确保在使用之前使用C#6.

  • 如此聪明,滥用和代码不清楚的潜力很大:).但好的选择. (2认同)