I’ve written identical code for DataSet and DataTable. Can this be DRY’d?

huangapple go评论65阅读模式
英文:

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&lt;T&gt;(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.

huangapple
  • 本文由 发表于 2023年5月14日 06:42:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76245154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定