简体   繁体   English

在多种情况下使用一种方法

[英]Using one method for multiple scenarios

I'm developing a web app using Asp.net webforms. 我正在使用Asp.net Webforms开发一个Web应用程序。 The requirement is to populate a gridview based on selected value from dropdown which I can achieve no problem. 要求是根据从下拉列表中选择的值来填充gridview,我没有问题。 What I'm trying to do is minimize my code so I don't have to repeat myself. 我想做的是将代码最小化,因此我不必重复自己。 So I've created a method which returns a DataTable from the query that is passed in as a parameter to that function. 因此,我创建了一个方法,该方法从查询中返回DataTable表,该DataTable作为参数传递给该函数。

public DataTable GetData(string Query)
{
 //Do stuff i.e. sql reader 
  ...
}

Some of the Sql quesries will have params and others won't eg 一些Sql查询将具有参数,而另一些则不会

  1. SELECT TESTONE FROM MY TABLE WHERE TESTONE = @param
  2. SELECT TESTTWO FROM MY TABLE

I want to be able to call GetData() method with both of the above queries but I can't figure out how to extend my function to accommodate for both scenarios. 我希望能够通过以上两个查询调用GetData()方法,但是我不知道如何扩展我的函数以适应这两种情况。 If someone can guide me I would highly appreciate it. 如果有人可以指导我,我将不胜感激。

Would using a GetData(string Query, Dictionary<string, object> parameters) be a overkill in this case? 在这种情况下GetData(string Query, Dictionary<string, object> parameters)使用GetData(string Query, Dictionary<string, object> parameters)会过大?

I managed to figure this out by making the following changes to the my code. 通过对代码进行以下更改,我设法弄清了这一点。

public DataTable GetTrainingData(string query, params string[] parameters)
{
 // Do work here
}

I can now call the same method for both of my queries as 我现在可以为两个查询调用相同的方法

  1. GetTrainingData("SqlQuery")
  2. GetTrainingData("SqlQuery", parameters)

Further reading on params key word here and here 这里这里进一步阅读params关键字

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

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