是否可以从同一表单上的其他 private string
访问 private void
而不是其他表单?
private void english()
{
string value1 = "Hello!";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = value1;
}
错误是:当前上下文中不存在名称“value1”
答案 0 :(得分:1)
您正在尝试访问另一个方法中的局部变量。局部变量是在方法范围内声明的变量(在您的情况下 - 在方法english()
中。这些变量只能从同一方法访问。
但是,你可以做的是在方法english()
之外创建一个类字段,在这种情况下,它可以从这个类的任何非静态方法访问:
private string value1;
private void english()
{
value1 = "Hello!";
}
private void button1_Click(object sender, EventArgs e)
{
label1.Text = value1;
}
答案 1 :(得分:1)
与上一个答案一样。范围定义了变量的可用位置。 如果你是c#的新手,范围可以被视为括号的“花哨名称”。
class Program
{
private string _sPrivate; //This is a private variable, only accessable to methods within the class.
public string PublicString; //This is a public variable, it is accessable outside the class.
private void _privateMethod(string this_is_an_argument) //This is a method, since it is private, it is only available inside the above class.
{
string thisIsAvar; //this has been defined inside _privateMethod, and is ONLY available inside _privateMethod.
}
public void PublicMethod() //This is a public method. It can be called outside the class, on the class itself. Code running in here can still access the private variables inside the class.
{
_sPrivate = "I just changed the private var"; //This will work.
thisIsAvar = "This is impossible, because thisIsAvar doesn't exist here"; //This will throw an error. Since thisIsAvar isn't defined inside this scope.
}
}