将value更改为全局变量,并在其他类中获取它的值

本文关键字:其他 获取 value 全局变量 | 更新日期: 2023-09-27 17:52:11

我在类"X"中有一个全局变量,public int fileCounter = 0;

在这个类的一个方法中,我将

的值增加到n…"fileCounter + +";

我需要在其他类中获取这个值,问题是此时返回值为0

我该怎么做?

将value更改为全局变量,并在其他类中获取它的值

这听起来像是您在一个类中有一个公共字段(或属性),并希望在另一个类中使用该值。

public class Foo
{
    public int FileCounter;
    public void SomeMethod()
    {
        FileCounter++;
    }
}
public class Bar
{
    public void SomeMethod()
    {
        var foo = new Foo();
        foo.SomeMethod();
        Debug.WriteLine( string.Format("FileCounter: {0}", foo.FileCounter ) );
    }
}

请记住,字段是基于实例的,除非您将它们声明为静态。