在c ++中创建一个静态初始化类

时间:2015-07-20 15:56:01

标签: c++ oop static-members

我希望有一个用于一次性初始化的类,如下所示:

public ActionResult CopyJob(Int32 id)
        {
            string ReturnMessage;
            ReturnMessage = "";
            using (SqlConnection connection = new SqlConnection())
            {
                //string connectionStringName = this.DataWorkspace.CooperData.Details.Name;
                connection.ConnectionString =
                    ConfigurationManager.ConnectionStrings["PSAContext"].ConnectionString;
                string procedure = "PSA.dbo.CopyJob";
                using (SqlCommand command = new SqlCommand(procedure, connection))
                {
                    command.CommandType = CommandType.StoredProcedure;
                    command.CommandTimeout = 300;

                    command.Parameters.Add(
                        new SqlParameter("@SourceJobID", id));
                    SqlParameter ErrorString = new SqlParameter("@ErrorString", ReturnMessage);
                    ErrorString.Direction = ParameterDirection.Output;
                    ErrorString.Size = 4000;
                    command.Parameters.Add(ErrorString);


                        connection.Open();
                        command.ExecuteNonQuery();

                        // Save Output Param

                        ReturnMessage = ErrorString.Value.ToString();
                        @ViewBag.Results = ReturnMessage;

                }
            }
            return PartialView("_SPResults");
        }

当我运行上面的命令时,我发现'Initialise'类的构造函数永远不会在调试器中被命中。这是为什么?

1 个答案:

答案 0 :(得分:6)

您没有定义staticStuff,您只是声明了它。

你必须在类之外声明它:

Initialise  SomeClass::staticStuff;

Here is a live example.

此外,正如Borgleader指出的那样,您应该考虑使用member initializer list来改进您的代码。