This question already has answers here:
Why must a variable be declared outside of the scope of an if statement in order to exist?
                                
                                    (7个答案)
                                
                        
                                9个月前关闭。
            
                    
我想将字符串值从函数传递到内部函数。

private void datagrid_customer_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    for (int i = 0; i < datagrid_customer.Items.Count; i++)
    {
        if (Convert.ToString((datagrid_customer.SelectedCells[3].Column.GetCellContent(datagrid_customer.SelectedItem) as TextBlock).Text) == Convert.ToString((datagrid_customer.SelectedCells[1].Column.GetCellContent(datagrid_customer.Items[i]) as TextBlock).Text))
        {
            ...
            string a = (b + c + d).ToString();
        }
 }


我想将a传递给另一个函数

datagrid_customer.SelectAll();

for (int i = 0; i < datagrid_customer.Items.Count; i++)
{
    if (Convert.ToString((datagrid_customer.SelectedCells[43].Column.GetCellContent(datagrid_customer.Items[i]) as TextBlock).Text) == "0")
    {
        ...
         txt_f1.Text = a ;
    }
}


我需要txt_f1.text = a,但我无权使用a

我该怎么办?

最佳答案

如果创建了另一个函数,则可以将其作为参数传递给函数,例如:

int OtherFunction(string a)
{
    // your code here
}


然后只需像下面这样调用您的函数:

OtherFunction(a);


如果不是您创建的其他方法(例如单击事件的方法)或其他方法,则应将变量设为全局变量,这在两个范围内均有效:

public string a = ""; // in your main class


然后:

void function1()
{
    //some code
    a = "some value";
    //some code
}


int OtherFunction()
{
    // you have access to a in here to
    textBox1.Text = a;
}


编辑:(在您自己的示例中声明变量的展示)

string a = "";  //declare it here before (outside) method not inside it
private void datagrid_customer_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    for (int i = 0; i < datagrid_customer.Items.Count; i++)
    {
        if (Convert.ToString((datagrid_customer.SelectedCells[3].Column.GetCellContent(datagrid_customer.SelectedItem) as TextBlock).Text) == Convert.ToString((datagrid_customer.SelectedCells[1].Column.GetCellContent(datagrid_customer.Items[i]) as TextBlock).Text))
        {
            ...
            a = (b + c + d).ToString();
        }
 }

07-24 09:50
查看更多