英文:
I've written identical code for DataSet and DataTable. Can this be DRY'd?
问题
我发现我写了两次相同的代码。有这个,使用 DataSet
public static DataSet foo(SqlCommand)
{
var Adaptor = new SqlDataAdapter(Command);
// 重要的一行:
DataSet Output = new DataSet();
Adaptor.Fill(Output);
return(Output)
}
和这个,使用 DataTable
public static DataTable foo(SqlCommand)
{
var Adaptor = new SqlDataAdapter(Command);
// 重要的一行:
DataTable Output = new DataTable();
Adaptor.Fill(Output);
return(Output)
}
有没有办法消除这种重复?我的泛型尝试失败了,因为编译器无法知道我传入的内容始终可以安全地进行 Fill
。
英文:
I find that I've written the same code twice. There's this, with DataSet
public static DataSet foo(SqlCommand)
{
var Adaptor = new SqlDataAdapter(Command);
// The important line:
DataSet Output = new DataSet();
Adaptor.Fill(Output);
return(Output)
}
and this with DataTable
public static DataTable foo(SqlCommand)
{
var Adaptor = new SqlDataAdapter(Command);
// The important line:
DataTable Output = new DataTable();
Adaptor.Fill(Output);
return(Output)
}
Is there any way to remove this repetition? My attempts with generics have failed, since the compiler can't know that what I'm passing in is always safe to Fill
.
答案1
得分: 1
No, this code can't be DRY'd because there's no Fill
overload that takes in an interface or a class that is a common base to both DataSet
and DataTable
.
There's also no way to use generic constraints in the form of or - You can't have a generic method where T is one of several unrelated types (by related I mean, of course, polymorphic interchangeable) so attempting to write your method like static T foo<T>(SqlCommand cmd) where T : DataSet or T : DataTable
will not compile.
However, given the fact that these are only four lines of code that's being duplicated, I think it's not really a problem.
英文:
No, this code can't be DRY'd because there's no Fill
overload that takes in an interface or a class that is a common base to both DataSet
and DataTable
.
There's also no way to use generic constraints in the form of or -
You can't have a generic method where T is one of several unrelated types (by related I mean, of course, polymorphic interchangeable) so a attempting to write your method like static T foo<T>(SqlCommand cmd) where T : DataSet or T : DataTable
will not compile.
However, given the fact that these are only four lines of code that's being duplicated, I think it's not really a problem.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论