c#范围问题

标签 c# scope

抱歉这个愚蠢的问题。我刚开始 C# 编程。我已经为此研究了好几个小时,并在这里阅读了我可以阅读的内容。这看起来很常见,我只是不明白为什么它不起作用。我想在父方法中声明一个变量并更改子类中的值。如果这不是实现它的方法,我如何制作返回有用数据的方法(甚至是 for 循环或 while 循环)?

示例 1:

   static void Main(string[] args)
    {
        int rowID;
        for (int i = 1; i < 500; i++ )
        {
            rowID = i;
        }
        Console.WriteLine(rowID);
    }

示例 2:

private void SendButtonClicked(object sender, System.EventArgs e)
{            
    // finds the first row that has not been sent
    int rowID = GetMessageRow();
    //then process the row and figure out what stored procedure to run 
    RunStoredProcedure(rowID);
}

public int GetMessageRow()
// finds the first row that has not been sent
{
    int rowID;
      // skipping some code
       while (drGetMessageRow.Read())
        {
         // while loop does not understand the variable and errors  
            rowID = drGetMessageRow.GetInt32(0);
            MessageBox.Show("1: RowID is " + rowID.ToString());
        }
}

最佳答案

使用return 关键字从方法中返回一个值。这个关键字退出方法。示例:

 return rowID;

关于c#范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6636543/

相关文章:

azure - 如何使用 Terraform 在管理组范围上定义和分配 Azure 策略?

c# - Identity Server 4 与身份相关的范围请求,但没有 openid 范围

c++ - 从外部对象调用方法时,qt 的 gui 线程是否会在后台生成线程?

c# - ConcurrentDictionary 和 ConcurrentQueue 的这种组合是线程安全的吗?

c# - 在没有公共(public)构造函数的情况下模拟密封类?

c# - 非阻塞书签有什么意义以及如何恢复到它?

c# - '集合已修改;使用 async/await 可能无法执行枚举操作

c# - 将 wait.until 与 selenium 一起使用时如何记录超时时间?

python - 如何在方法中的字符串外部使用三引号字符串(使用 eval())中定义的参数?

javascript - AngularJS 如何在另一个 ngController 中访问一个 ngController 的参数