如何在课堂上访问静态方法

时间:2017-04-01 14:07:47

标签: c#

这里我在静态方法中编写一些代码,在类文件中请帮助我如何创建静态类的实例

public class ConnectionString
    {

       public static void CreateCommand(string querystring, string connectionString)
        {
           using(SqlConnection cn = new SqlConnection(connectionString))
           {
               SqlCommand cmd = new SqlCommand(querystring, cn);
               cmd.Connection.Open();
               cmd.ExecuteNonQuery();
           }           
        }

    }

2 个答案:

答案 0 :(得分:2)

就这样称呼它:

string querystring = "Your values here";
string connectionString = "Your values here";
ConnectionString.CreateCommand(querystring, connectionString);

那就是它。

答案 1 :(得分:0)

您的ConnectionString类可以重构为实现这样的接口:

  public interface IDataAccess
    {
        void CreateCommand(string querystring, string connectionString);
    }

此接口允许我们将其实现注入您在注释中提到的控制器中。因此,您的ConnectionString类(重命名为更有意义的名称DataAccess)应如下所示:

 public class DataAccess : IDataAccess
    {       

        public void CreateCommand(string querystring, string connectionString)
        {
            using (SqlConnection cn = new SqlConnection(connectionString))
            {
                cn.Open();
                using (SqlCommand cmd = new SqlCommand(querystring, cn))
                {
                    cmd.ExecuteNonQuery();
                }             
            }
        }
    } 

然后在您的控制器/客户端类中,您可以在运行时注入具体实现。

public class DataController : Controller
{
    private readonly IDataAccess dataAccess;
    public DataController(IDataAccess dataAcces)
    {
        this.dataAccess = dataAcces;
    }

    public ActionResult ShowData()
    {
        string querystring = "you t-sql query";
        string connectionString = "<you sql connection string>";

        this.dataAccess.CreateCommand(querystring, connectionString);

        return this.View();
    }
} 

如果您正在使用MVC并且不知道如何解决依赖关系,请参阅this article

或者你可以像这样新建一个DataAccess类的实例:

public class DataController : Controller
    {
        private readonly IDataAccess dataAccess;
        public DataController()
        {
            this.dataAccess = new DataAccess();
        }

        public ActionResult ShowData()
        {
            string querystring = "you t-sql query";
            string connectionString = "<you sql connection string>";

            this.dataAccess.CreateCommand(querystring, connectionString);

            return this.View();
        }
    }

我不会推荐这种方法,因为它不可能进行单元测试。

希望这有帮助!