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

本文关键字:调用 变量 情况下 | 更新日期: 2023-09-27 17:58:14

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

 class foo
 {
    public const bool x = true;
 }

有没有什么方法可以在不执行foo.x的情况下使用x?

我想这样使用它:

if( x ) 

而不是这样:

if( foo.x )

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

实现这一点的唯一方法是将foo标记为静态,并在希望访问foo.x的位置使用using static作为x

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

以及更高版本:

using static Foo.Bar;
Console.WriteLine(x);

using static是C#的一个特性,所以在使用它之前,请确保您正在使用C#6。

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

所以这是可行的:

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在某种程度上隐藏这个真相。尽管如此,它还是在课堂上被调用的。

对于初学者来说,它需要是可公开访问的

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

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

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