在静态函数中使用new关键字创建对象时发生了什么

时间:2017-12-06 03:30:20

标签: c# singleton

到目前为止,这是我的代码:

/languages/

我的问题是关于GetInstance方法:

public class ServerUtility
{
    public static int LogError(string source, string detail)
    {
        int iresult = -99;
        try
        {
            BaseRepository repo = new BaseRepository();
            using (SqlConnection con = new SqlConnection(repo.connectionString))
            {
                con.Open();
                using (SqlCommand cmd = new SqlCommand($"INSERT INTO [dbo].[LogError]([source],[detail],[date])VALUES('{source.Replace("'", "''")}','{detail.Replace("'", "''")}',GETDATE());SELECT @@IDENTITY", con))
                {
                    string getValue = cmd.ExecuteScalar().ToString();
                    iresult = Convert.ToInt32(getValue);
                } // command disposed here

            } //connection closed and disposed here
        }
        catch (Exception ex) { throw ex; }
        return iresult;
    }
}

我总是把它设置为我的静态函数的新对象,只是为了从AppSetting中获取常量值。

如果我将此代码实现到我的项目中,实际发生了什么? 表现怎么样?

是否会导致性能问题?

由于

1 个答案:

答案 0 :(得分:0)

就像提到的@gtosto一样,你没有正确实现单身。

应该是:

    public static SenderBackupProvider GetInstance()
    {            
        if (oInstance == null)
        {
            oInstance = new SenderBackupProvider(CommFunction.GetLogNumber(CommonConst.APPID));
        }

        return oInstance;
    }

查看Implementing the Singleton Pattern in C#

编辑:

由于OP并不认为oInstance变量在首次运行时应该为空,这里是一个截图。

enter image description here

仔细查看代码后,您正在使用Web应用程序。静态变量的生命周期因平台而异。您可能需要在IIS中重新启动应用程序域。请参阅Lifetime of ASP.NET Static Variable

中的详细信息