简体   繁体   English

c# 变量 scope

[英]c# Variable scope

All,全部,

I'm having some problems with the scope of SqlConnection RTTConn.我在使用 SqlConnection RTTConn 的 scope 时遇到了一些问题。

My code is as follows:我的代码如下:

namespace RTT_API
{
    public partial class Request : Form
    {
        private static readonly HttpClient client = new HttpClient();
        private static SqlConnection RTTConn;

        public Request()
        {
            InitializeComponent();
        }



        private void Request_Load(object sender, EventArgs e)
        {

            string connString = @""; << I removed the connection string just for this post

        option 1
            SqlConnection RTTConn = new SqlConnection(connString);
        
        option 2            

        RTTConn.ConnectionString = connString; << "Object reference not set to an instance of an object"
            RTTConn.Open();
            
        }

        private void cmbRefresh_Click(object sender, EventArgs e)
        {
            MessageBox.Show(RTTConn.State.ToString()); << Option 1 - "Object reference not set to an instance of an object"
        ProcessRepositories();
        }

    }

}


If I use option 1 then I get the error in the error in cmbRefresh.如果我使用选项 1,那么我会在 cmbRefresh 的错误中得到错误。 I've think I've created two instances of the variable - one at the class level and one in the request_load code?我认为我已经创建了变量的两个实例——一个在 class 级别,一个在 request_load 代码中? Therefore the one at the class level hasn't had an object assigned to it?因此,class 级别的那个没有分配给它的 object?

If I use option 2 then I get the error in request_load.如果我使用选项 2,那么我会在 request_load 中收到错误。 I think this is because I haven't created the object?我想这是因为我还没有创建 object?

I would appreciate help with two questions?:我会感谢两个问题的帮助?:

  1. Is my understanding above correct?我上面的理解正确吗?
  2. Which is the best way to correct it?纠正它的最佳方法是什么? I could change the class level declaration to:我可以将 class 级别声明更改为:
SqlConnection RTTConn = new SqlConnection("ConnectionString");

However I don't know if that's the correct way?但是我不知道这是否是正确的方法?

The answers from Klaus and Damien_The_Unveliever are both correct. Klaus 和 Damien_The_Unveliever 的答案都是正确的。 I can't accept them as they are comments so I'm adding an answer referencing them.我不能接受它们,因为它们是评论,所以我添加了一个引用它们的答案。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM