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

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

问题描述

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

例如:

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

For example:

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;          
}

因此,在此示例中,我需要从函数button2_Click()

So 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. 将数据保留在服务器端的其他方法,等等.

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

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