Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#如何将全局变量的写入限制为仅对其进行初始化的类(以便其他类只能读取它)?_C#_.net - Fatal编程技术网

C#如何将全局变量的写入限制为仅对其进行初始化的类(以便其他类只能读取它)?

C#如何将全局变量的写入限制为仅对其进行初始化的类(以便其他类只能读取它)?,c#,.net,C#,.net,正如标题所述,我正在寻找解决以下问题的方法: namespace Test { public partial class SetVariable : Form { public string test = ""; public SetVariable() { InitializeComponent(); } private void button2_Click(object

正如标题所述,我正在寻找解决以下问题的方法:

namespace Test
{
    public partial class SetVariable : Form
    {
        public string test = "";

        public SetVariable()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            test = "test"
        }
    }
}
在第二种形式中,我想阅读它,但也想限制用户对变量进行任何更改(出于偶然或故意),因为所有变量都只能在SetVariable形式中设置,然后在计划的所有其他形式中使用

namespace Test
{
    public partial class GetVariable : Form
    {
        public GetVariable()
        {
            InitializeComponent();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (SetVariable.test == "test")
            { //doSomething;}
            }
        }
    }
}
如果我将该变量设置为公共只读,那么我就不能按照应该写入的形式写入它。是否有另一种初始化全局变量的方法,该全局变量只能以其创建位置的形式进行更改? 提前感谢。

更改:

public string test = "";
致:


另请参见。

将公共属性设置为私有

public partial class SetVariable : Form
{
  public string Test {get; private set;}

  //Just in case if you want to set value to Test property from other class.
  //If you want Test property readonly to other 
  //class you don't need this method.
  public void SetTest(string test)
  {
    Test = test;
  }
}

public class Main
{
  SetVariable sv = new SetVariable();
  sv.SetTest("Some Value"); //unwanted to scenario. Just in case if you want

  //read Test value
  string testValue = sv.Test; //allowed
  //set Test value
  sv.Test = "Other value"; //not allowed.
}

非常感谢你的回答,这对我以后的课程很有帮助。也谢谢你的例子=)祝你愉快。谢谢你的回答和进一步描述这个provate属性的其他帖子。祝您今天过得愉快
public partial class SetVariable : Form
{
  public string Test {get; private set;}

  //Just in case if you want to set value to Test property from other class.
  //If you want Test property readonly to other 
  //class you don't need this method.
  public void SetTest(string test)
  {
    Test = test;
  }
}

public class Main
{
  SetVariable sv = new SetVariable();
  sv.SetTest("Some Value"); //unwanted to scenario. Just in case if you want

  //read Test value
  string testValue = sv.Test; //allowed
  //set Test value
  sv.Test = "Other value"; //not allowed.
}