C#从另一个方法引用变量

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9301197/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 06:47:58  来源:igfitidea点击:

C# referencing a variable from another method

c#methodscall

提问by Zbone

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

For example:

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

例如:

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

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

所以在这个例子中,我需要从函数中调用函数中定义的字符串“ abutton1_Click()button2_Click()

Thanks!!

谢谢!!

采纳答案by David

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

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.

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

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

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

  1. Page Values (hidden fields, for example)
  2. Cookies
  3. Session Variables
  4. Application Variables
  5. A Database
  6. A Server-Side File
  7. Some other means of persisting data on the server side, etc.
  1. 页面值(例如隐藏字段)
  2. 饼干
  3. 会话变量
  4. 应用变量
  5. 数据库
  6. 服务器端文件
  7. 在服务器端保存数据的其他一些方法等。

回答by northpole

make is a class level variable (global variable) or create a getter and setter for String a, to name a couple options.

make 是一个类级变量(全局变量)或为 String a 创建一个 getter 和 setter,以命名几个选项。

回答by phoog

You can't do that. string ais a local variable declaration.It's called "local" because it is only accessible "locally" to the block in which it occurs.

你不能那样做。 string a局部变量声明。它被称为“本地”,因为它只能“本地”访问它出现的块。

To make the variable visible to both methods, you can create a field in the class containing the methods. If the methods are in different classes, though, the solution gets more complicated.

要使变量对两种方法都可见,您可以在包含这些方法的类中创建一个字段。但是,如果方法在不同的类中,则解决方案会变得更加复杂。

回答by DaveShaw

You need to declare string ain the scope of the class, not the method, at the moment it is a "local variable".

您需要string a在 的范围内声明class,而不是方法,目前它是一个“局部变量”。

Example:

例子:

private string a = string.Empty;

public void button1_Click(object sender, EventArgs e) 
{  
    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;           
} 

You can now access the value of your "private field" afrom anywhere inside your classwhich in your example will be a Form.

您现在可以aclass您的示例中的Form.

回答by Yuck

Refactor that into a method call (or property) so you can access the value of aelsewhere in your application:

将其重构为方法调用(或属性),以便您可以访问a应用程序中其他地方的值:

public String GetStringAValue() {
    return "help";
}

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

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

Also note that you could be using implicit type declarations. In effect, these are equivalent declarations:

另请注意,您可能正在使用隐式类型声明。实际上,这些是等效的声明:

string a = GetStringAValue();
var a = GetStringAValue();

回答by BlackBear

You can't do this because those variables are in different scopes(think it as being hidden). The only way to achieve this is to move a in the main form class:

你不能这样做,因为这些变量在不同的范围内(认为​​它是隐藏的)。实现这一点的唯一方法是在主窗体类中移动 a:

public partial class Form1 : Form
{
    string a;

    // etc ...
}

回答by m-y

class SomeClass
{
    //Fields (Or Properties)
    string a;

    public void button1_Click(object sender, EventArgs e)
    { 
        a = "help"; //Or however you assign it
    }

    public void button2_Click(object sender, EventArgs e)
    {
        string b = "I need";
        string c = b + (a ?? String.Empty); //'a' should be null checked somehow.
    }
}

回答by AwesomeHemu

You could save the variable into a file, then access the file later, like this:

您可以将变量保存到文件中,然后稍后访问该文件,如下所示:

public void button1_Click(object sender, EventArgs e)
{ 
    string a = "help";
    File.WriteAllText(@"C:\myfolder\myfile.txt", a); //Change this to your real file location
}

public void button2_Click(object sender, EventArgs e)
{
    string d = File.ReadAllText(@"C:\myfolder\myfile.txt");

    //this is where I need to call the string "a" value from button1_click 
    string b = "I need";
    string c = b + d; //Instead of a, put the variable name (d in this case)          
}

If you do that, just make sure to put this in your code: using System.IO;

如果您这样做,请确保将其放入您的代码中: using System.IO;

回答by Shubham Khare

Agree with @Devid 's answer but I prefer to create a class of required entities and then use them in entire solution without passing variable as argument.

同意@Devid 的回答,但我更喜欢创建一类必需的实体,然后在整个解决方案中使用它们,而不将变量作为参数传递。

Classname.variableName;

for ex-

对于前-

 Class argumentData{
public static string firstArg= string.Empty;
public static string secArg= string.Empty;
}

Say I am assigning data in function

假设我在函数中分配数据

void assignData()
{
argumentData.firstArg="hey";
argumentData.secArg="hello";
}

if I want to use it in another method then

如果我想在另一种方法中使用它,那么

void showData()
{
Console.WriteLine("first argument"+argumentData.firstArg);
Console.WriteLine("sec argument"+ argumentData.secArg);
}

Hope this helps!

希望这可以帮助!

回答by sivabalan



you can use session here

你可以在这里使用会话

public void button1_Click(object sender, EventArgs e)
{ 
string a = "help";
Session["a"]=a;
}
public void button2_Click(object sender, EventArgs e)
{ 
string d=Session["a"].ToString();        
string b = "I need ";
string c = b + d;          
}