gpt4 book ai didi

c# - 关于过载的最佳做法是什么

转载 作者:行者123 更新时间:2023-11-30 13:17:01 25 4
gpt4 key购买 nike

我想知道什么是最佳实践,或者至少什么是关于重载的更标准做法。我使用的是 c# 3.5,所以我没有可选参数。假设我有以下方法:

Foo(string param1, string param2)
{
SqlConnection connection = SM.Program.GetConnection();
SqlCommand command = connection.CreateCommand();

command.CommandText = "UPDATE Table" +
"SET Pla = @pla " +
"WHERE Foo = @foo";

try
{
command.Parameters.AddWithValue("@pla", param1);
command.Parameters.AddWithValue("@foo", param2);
connection.Open();
command.ExecuteNonQuery();
}
finally
{
connection.Dispose();
command.Dispose();
}
}

而且我需要一个带有另一个参数的重载,比方说一个 sqltransaction

Foo(string param1, string param2, SqlTransaction trans)

第二种方法基本相同,但它会在事务中进行操作

现在我想知道我该怎么办?只有 1 种方法接受空参数作为事务,在这种情况下不使用任何或 2 种方法,但除了事务之外相当多的复制/粘贴代码?

什么被认为是这种事情的最佳实践?

编辑:我认为一般的想法似乎是在重载之间进行链接。但我仍然想知道,在那种情况下,在方法中不接受 null 参数是不是一种坏事?

最佳答案

按照 DRY principle 进行, 你不应该复制粘贴代码。

因此,有两个这样的方法,您应该始终有某种链接。

public void Foo(string param1, param2) {
Foo(param1, param2, null);
}

public void Foo(string param1, string param2, SqlTransaction trans) {
//do stuff, handle null value for trans
}

关于默认参数的更新

在某些情况下,用单个方法提供默认参数而不是重载可能被认为是不好的做法,尤其是在编写库时:

//assembly1.dll
public void Foo(int a, int b, int c = 3) { ... }

//assembly2.dll
void Bar() {
Foo(1,2);
}

编译器将调用 Foo(1,2) 替换为 Foo(1,2,3)

现在,假设我们要将 c 的默认值更改为 4,并在不更改 assembly2.dll 的情况下更新 assembly1.dll。

我们期望调用 Foo(1,2,4) 但实际上 Foo(1,2,3) 仍然被调用,因为默认值存储在调用者的位置!

通过使用重载,默认值 3 存储在它所属的 assembly1.dll 中。

关于c# - 关于过载的最佳做法是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17342641/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com