从另一个方法引用变量 [英] Referencing a variable from another method

查看:33
本文介绍了从另一个方法引用变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 C# 新手,我真的需要知道如何从另一个方法调用/使用字符串.

I'm new to C# and I really need to know how to call/use a string from another method.

例如:

public void button1_Click(object sender, EventArgs e)
{ 
    string a = "help";
}

public void button2_Click(object sender, EventArgs e)
{
    //this is where I need to call the string "a" value from button1_click 
    string b = "I need ";
    string c = b + a;          
}

在这个例子中,我需要调用字符串a";在函数 button2_Click()

In this example I need to call string "a" defined in function button1_Click() from function button2_Click()

推荐答案

通常您会将它作为参数传递,如下所示:

Usually you'd pass it as an argument, like so:

void Method1()
{
    var myString = "help";
    Method2(myString);
}

void Method2(string aString)
{
    var myString = "I need ";
    var anotherString = myString + aString;
}

但是,您示例中的方法是事件侦听器.你通常不会直接打电话给他们.(我想你可以,但我从来没有找到一个应该的实例.)所以在这种特殊情况下,将值存储在一个共同的两个方法在类中的位置.像这样:

However, the methods in your example are event listeners. You generally don't call them directly. (I suppose you can, but I've never found an instance where one should.) So in this particular case it would be more prudent to store the value in a common location within the class for the two methods to use. Something like this:

string StringA { get; set; }

public void button1_Click(object sender, EventArgs e)
{ 
   StringA = "help";
}

public void button2_Click(object sender, EventArgs e)
{
    string b = "I need ";
    string c = b + StringA;
}

但是请注意,这在 ASP.NET 中的行为会非常不同.因此,如果这就是您正在使用的,那么您可能希望更进一步.它行为不同的原因是因为服务器端是无状态的".因此,来自客户端的每个按钮点击都会产生一个全新的类实例.因此,在第二个按钮单击事件处理程序中使用它时,不会反映在第一个按钮单击事件处理程序中设置该类级别成员.

Note, however, that this will behave very differently in ASP.NET. So if that's what you're using then you'll probably want to take it a step further. The reason it behaves differently is because the server-side is "stateless." So each button click coming from the client is going to result in an entirely new instance of the class. So having set that class-level member in the first button click event handler won't be reflected when using it in the second button click event handler.

在这种情况下,您需要查看 Web 应用程序中的持久状态.选项包括:

In that case, you'll want to look into persisting state within a web application. Options include:

  1. 页面值(例如隐藏字段)
  2. 饼干
  3. 会话变量
  4. 应用变量
  5. 数据库
  6. 服务器端文件
  7. 其他一些在服务器端保存数据的方法,等等.

这篇关于从另一个方法引用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆