【问题标题】:Call the method in an internal function c# [duplicate]在内部函数c#中调用方法[重复]
【发布时间】:2019-03-24 19:30:13
【问题描述】:

我想将字符串值从函数传递到内部函数。

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

我该怎么办?

【问题讨论】:

  • if 声明的范围之外声明string a。您仍然可以在 if 语句中分配它,但如果您也在那里声明它,它就会超出范围。请参阅我上面链接的重复帖子。
  • string a 将对datagrid_customer_SelectionChanged 中的其余代码可见。在你的第一个循环之前声明string a;

标签: c# wpf visual-studio function


【解决方案1】:

如果你已经创建了另一个函数,那么你可以将它作为参数传递给你的函数,例如:

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

【讨论】:

  • 当我创建函数并粘贴我的代码然后在 datagirid 中显示错误。程序不知道数据网格
  • 大多数错误已修复,但当我返回“a”时显示错误 “无法将类型字符串隐式转换为 int”
  • @emadshn 您应该将其解析为 int:int q = int.Parse(a);
  • 当点击按钮时,程序崩溃并在“int.parse(a);”中显示错误输入字符串格式不正确。
  • 那么a 的值不是数字,不能解析为int,例如,如果a = "123"int q = int.Parse(a); 可以工作,q = 123 但如果@ 987654332@ 则无法解析为 int。但是它与这个问题无关。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 1970-01-01
  • 2017-08-07
  • 1970-01-01
  • 1970-01-01
  • 2013-06-27
  • 2014-11-13
相关资源
最近更新 更多