如何创建在调用中使用其他函数的通用函数。 [英] How do I create a generic function that uses other functions in the call.
本文介绍了如何创建在调用中使用其他函数的通用函数。的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试消除一堆遵循此模式的重复代码:
I am trying to eliminate a bunch of duplicated code that follows this pattern:
protected OdbcConnection Connection { get; set; }
protected OdbcCommand Command { get; set;}
protected OdbcDataReader Reader { get; set; }
public string BuildQuery (string parm)
{
string query = string.Empty;
// build query
return query;
}
public void ProcessDataFromReader()
{
// do something with reader
}
public void GetData()
{
Command.CommandText = BuildQuery("parms");
using (Reader = Command.ExecuteReader())
{
while (Reader.Read())
{
ProcessDataFromReader();
}
}
}
我想创建一个处理上述方法的通用方法但允许这两个函数可以互换:
* ProcessDataFromReader()
* BuildQuery(parms)
谢谢
我正在尝试构建一个类似的通用方法:
I want to create a generic method that handles the methodology above but allow the two functions to be interchangable:
* ProcessDataFromReader()
* BuildQuery("parms")
Thanks
I am trying to build a generic method something like:
public void GetData<T>(Func<object[], string> TQuery, Func<T> TRead)
{
Command.CommandText = (string)TQuery();
using (Reader = Command.ExecuteReader())
{
while (Reader.Read())
{
TRead();
}
}
}
所以我可以有多个查询来执行并且能够读取查询的结果,而不必一遍又一遍地写相同的模式。
so I can have several queries to execute and be able to read the results of the queries without having to write the same pattern over and over.
推荐答案
我想我有解决方案:
I think I have the solution:
{
public class Class1
{
protected OdbcConnection Connection { get; set; }
protected OdbcCommand Command { get; set; }
protected OdbcDataReader Reader { get; set; }
public string BuildQuery1(string parm)
{
string query = string.Empty;
// build query
return query;
}
public string BuildQuery2(string parm1, double parm2)
{
string query = string.Empty;
// build query
return query;
}
public List<int> ProcessDataFromReader1()
{
// do something with reader
return new List<int>();
}
public List<double> ProcessDataFromReader2()
{
// do something with reader
return new List<double>();
}
public void GetGeneric()
{
Func<string> query = delegate { return this.BuildQuery1("parms"); };
Func<List<int>> read = delegate { return this.ProcessDataFromReader1(); };
GetData(query, read);
}
public void GetGeneric()
{
Func<string> query = delegate { return this.BuildQuery2("parms", 10d); };
Func <List<double>> read = delegate { return this.ProcessDataFromReader2(); };
GetData(query, read);
}
public void GetData<T>(Func<string> TQuery, Func<T> TRead)
{
Command.CommandText = TQuery();
using (Reader = Command.ExecuteReader())
{
while (Reader.Read())
{
TRead();
}
}
}
}
}
这篇关于如何创建在调用中使用其他函数的通用函数。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文