C# 在代码隐藏中,如何在同一命名空间内的另一个 class 中引用 public 变量?

C# In codebehind, how reference public variable in another class within the same namespace?

我有一个代码在同一个命名空间中有两个 classes。我想引用命名空间中第二个 class 中的第一个 classes public 变量。我知道我显然可以传递变量,但我想知道是否有办法引用它们。

namespace CADE.results
{
    public partial class benchmark : BasePage
    {
        public string numAnswers = "";   <-- like to reference this from GetScore()

        protected void Page_Load(object sender, EventArgs e)
        {
            BenchmarkAdd bma = new BenchmarkAdd();
            bma.GetScore();
        }
    }


    public class BenchmarkAdd
    {
        public BenchmarkAdd() 
        { 
        }
        public void GetScore() 
        {
            benchmark.numAnswers++;    <-- would like to reference public var here
        }
    }

}

我原以为 benchmark.numAnswers 可以,但事实并非如此。是否可以从 BenchmarkAdd class?

中引用 numAnswers

I'd like to reference the first classes public variables from the second class in the namespace.

numAnswers 是一个实例变量,所以 GetScore() 不知道要更新哪个实例。

完成此操作的唯一方法(不传递您的 Page 实例,或使用 ref 传递 numAnswers)是使 numAnswers static :

public static string numAnswers = "";

然后您可以在 GetScore() 中更新:

public void GetScore() 
{
    CADE.results.benchmark.numAnswers++;
}

但是,static 的效果是每个 benchmark 实例不再有自己的 numAnswers 字段;该字段将只有一个副本属于该类型本身。