【问题标题】:pass a string value between methods c#在方法c#之间传递一个字符串值
【发布时间】:2016-03-31 08:51:59
【问题描述】:

我有一个需要在整个程序中使用的公共字符串。

public string connectionString = null;

我赋值如下:

internal string accessString()
{
    return connectionString =
        @"Provider=Microsoft.ACE.OLEDB.12.0;" +
        @"Data Source=" + DBFileName + ";" +
        @"Persist Security Info=False";
}

当我第一次运行该方法时,该值是正确的,但是一旦该方法的执行完成,该值将返回为空。

internal void selectDB()
    {
        try
        {
            OpenFileDialog choofdlog = new OpenFileDialog();
            choofdlog.Filter = "All Files (*.*)|*.*";
            choofdlog.FilterIndex = 1;
            if (choofdlog.ShowDialog() == DialogResult.OK)
            {
                DBFileName = choofdlog.FileName;
                connectionString = accessString();
                Saveproducts();
            }
            MessageBox.Show(connectionString);

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }//select db ends

以上方法完美取值。

internal void writeContents()// read all the text files to the Data base
    {
        try
        {
            MessageBox.Show(connectionString);
}
}

上面的这个方法返回 null,即使它在第二个方法成功地为 connectionString 赋值之后运行。

如何解决这个问题,我不想使用静态

【问题讨论】:

  • 能否请您显示更多您使用它的类的代码?您何时致电accessString(),何时访问connectionString()
  • 很难确切地知道你做错了什么,但可能是由于某个对象的某些实例超出了范围 - 需要更多代码来确认,所有当前的答案都是推测性的(尽管使 connectionString 静态可能会起作用,但可能会导致其他问题,具体取决于您的应用)

标签: c# string methods properties


【解决方案1】:

使用 Session 存储连接字符串,也可以使用

connectionString as Static variable

那么它不会重置该值。

【讨论】:

    【解决方案2】:

    如何更改此值,以便该方法在整个过程中创建此值 程序

    你可以这样做,accessString 现在总是返回有效的连接字符串。

    public string connectionString = null;
    accessString();
    
    internal string accessString()
    {
        return string.IsNullOrEmpty(connectionString)? 
            @"Provider=Microsoft.ACE.OLEDB.12.0;" +
            @"Data Source=" + DBFileName + ";" +
            @"Persist Security Info=False" : connectionString;
    }
    

    【讨论】:

    • 据我所知,您不能在方法中使用 void 和 return
    • 啊……我的错,我忽略了它。感谢@ChongChing 现在正确。
    猜你喜欢
    • 2012-01-12
    • 2013-12-02
    • 2020-04-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-07
    • 1970-01-01
    • 2016-06-17
    相关资源
    最近更新 更多