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

时间:2016-07-21 13:56:27

标签: c# class

我想使用此类中的const变量:

 class foo
 {
    public const bool x = true;
 }

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

我想这样使用它:

if( x ) 

而不是这样:

if( foo.x )

3 个答案:

答案 0 :(得分:10)

实现这一目标的唯一方法是将let e = md5(this.email); 标记为静态,并使用using staticfoo作为foo.x访问。

x

以后:

namespace Foo
{
    static class Bar
    {
         public const bool x = true;
    }
}

using static Foo.Bar; Console.WriteLine(x); 是C#功能,因此请确保在使用之前使用C#6。

答案 1 :(得分:2)

不,成员始终是类的成员,因此您必须通过类名调用静态(或常量)变量,或者调用实例上的成员。

所以这会奏效:

public class Foo { public static int SomeInt {get;set;} = 12; }

int i = Foo.SomeInt;

或者:

public class Foo { public int SomeInt {get;set;} = 12; }

Foo f = new Foo();
int i = foo.SomeInt;

正如Marcin所示,你可以使用using static隐藏真相。不过,它是通过课堂调用的。

答案 2 :(得分:0)

首先,它需要公开访问

public class foo
{
    public const bool x = true;
}

然后您可以将值存储在变量

var x = foo.x;
if(x) { .. }