有什么方法可以创建可能具有不同的调用和返回参数对象的方法? [英] Is there any way that I can create a method that might have a different call and return parameter object?
问题描述
我正在使用这种类型的代码:
I am using this type of code:
lock (l)
{
try
{
var data = db2.Query<CardSetWithWordCount>(qry);
return data;
}
catch (Exception ex)
{
db2.Rollback();
Debug.WriteLine(ex);
Console.WriteLine(qry);
throw;
}
}
或其他类似示例:
lock (l)
{
try
{
var data = db2.Query<CardSetDetails>(qry);
return data;
}
catch (Exception ex)
{
db2.Rollback();
Debug.WriteLine(ex);
Console.WriteLine(qry);
throw;
}
}
除了db2.Query的返回类型不同的对象外,代码完全相同.
The code is exactly the same except for the different objects that are the return type of db2.Query.
由于要花费很多行,我想用一个我调用并传入返回对象和try字符串的方法替换这两个块.但是我不确定从哪里开始,因为在这种情况下返回的对象是
As it takes many lines I would like to replace these two blocks with a single method that I call and pass in the return object and a try string. But I am not sure where to start because the object returned which is in this case:
<CardSetWithWordCount>
对于我要替换的每种方法,
可以不同(例如).
could be different (such as )for each method I would like to replace.
这是我可以在方法中执行此操作的方式,如果可以,我将如何声明参数?
Is the way that I could do this in a method and if so how would I declare the parameters?
推荐答案
您可以使用以下泛型:
T RunQuery<T>(YourDB db, string qry)
{
lock (l)
{
try
{
T data = db.Query<T>(qry);
return data;
}
catch (Exception ex)
{
db.Rollback();
Debug.WriteLine(ex);
Console.WriteLine(qry);
throw;
}
}
}
这样称呼:
YourType res=RunQuery<YourType>(db2,qry);
请寻求更多信息: https://docs.microsoft.com/zh-CN/dotnet/csharp/programming-guide/generics/
这篇关于有什么方法可以创建可能具有不同的调用和返回参数对象的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!