gpt4 book ai didi

c# - C#重构问题

转载 作者:可可西里 更新时间:2023-11-01 08:38:23 24 4
gpt4 key购买 nike

我今天看到了下面的代码,我不喜欢它。它在做什么很明显,但我还是要在这里添加一点解释:

基本上,它从数据库中读取应用程序的所有设置,并遍历所有设置以查找数据库版本和应用程序版本,然后将一些变量设置为数据库中的值(稍后使用)。

我看了看,觉得它有点难看 - 我不喜欢 switch 语句,我讨厌在完成后继续遍历列表的东西。所以我决定重构它。

我想问大家的问题是你们将如何重构它?或者您认为它甚至根本不需要重构?

代码如下:

        using (var sqlConnection = new SqlConnection(Lfepa.Itrs.Framework.Configuration.ConnectionString))
{
sqlConnection.Open();

var dataTable = new DataTable("Settings");

var selectCommand = new SqlCommand(Lfepa.Itrs.Data.Database.Commands.dbo.SettingsSelAll, sqlConnection);
var reader = selectCommand.ExecuteReader();
while (reader.Read())
{
switch (reader[SettingKeyColumnName].ToString().ToUpper())
{
case DatabaseVersionKey:
DatabaseVersion = new Version(reader[SettingValueColumneName].ToString());
break;
case ApplicationVersionKey:
ApplicationVersion = new Version(reader[SettingValueColumneName].ToString());
break;
default:
break;
}
}

if (DatabaseVersion == null)
throw new ApplicationException("Colud not load Database Version Setting from the database.");
if (ApplicationVersion == null)
throw new ApplicationException("Colud not load Application Version Setting from the database.");
}

最佳答案

我的两分钱...

  1. 正如 Bobby 评论的那样,在每个一次性元素上使用 using
  2. 我会避免打开一个表并遍历所有记录,尽可能使用过滤器来获取值
  3. 如果根本不可能,请避免在字符串上使用 switch,因为只有两个选项可以对字符串执行 if else。与不区分大小写的选项相比,这样您就不必每次都创建 upper .
  4. 在读取 null 值之前检查它们以避免未处理的异常
  5. 如果您必须在代码中多次打开这种连接,您可以使用工厂方法为您提供连接。
  6. 当您已经知道要创建的对象类型时,我会避免使用“var”关键字。您通常会进行重构以增强代码的易读性。

关于c# - C#重构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3022600/

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