C# SqlCommand 命名约定

标签 c# sql asp.net coding-style naming-conventions

我对使用 C# 和 ASP.NET 还很陌生,我很好奇在 SQL 数据库上运行多个查询时是否有命名 SqlCommand 的约定。例如,我已经创建了我的 SqlConnection,我希望调用一个函数、两个存储过程,然后只创建一个常规的简单查询。目前,我正在使用:

SqlCommand function = new SqlCommand();
SqlCommand command = new SqlCommand();
SqlCommand proc1 = new SqlCommand();
SqlCommand proc2 = new SqlCommand();

对于这些不同的命令是否有更可接受的命名约定,或者我应该只使用一个命令,因为我在后面的代码块中使用 CommandText 和 CommandType 调用?

最佳答案

如果您在同一范围内有很多命令,您可以使用 personCommandproductCommand 这样的名称。来自MSDN General Naming Conventions你可以:

DO choose easily readable identifier names. For example, a property named HorizontalAlignment is more English-readable than AlignmentHorizontal.

DO favor readability over brevity. The property name CanScrollHorizontally is better than ScrollableX (an obscure reference to the X-axis).

DO NOT use underscores, hyphens, or any other nonalphanumeric characters. X DO NOT use Hungarian notation.

AVOID using identifiers that conflict with keywords of widely used programming languages.

查看更多关于 C# Coding Conventions 的信息.在其他情况下,我更喜欢只使用 command 而不是 Keep It Simple ,因为范围会告诉我。

另一个很好的提示,当您使用实现了IDisposable 接口(interface)的类型(如SqlCommandSqlConnection)时,您可以使用 using() { } 结构在此范围之后处理对象。例如:

public IEnumerable<Person> GetPersons()
{
    var result = new List<Person>();

    using (var connection = new SqlConnection("connection string"))
    {
       // I know it is a person command, because it is in a method for it.
       // Keep it simple!
       using (var command = new SqlCommand("select id, name from persons", connection))
       {
          using (var reader = command.ExecuteReader())
          { 
              while (reader.Read())
              {
                  result.Add(new Person() {
                     Id = (int) reader["id"];
                     Name = reader["name"] as string;                    
                  });
              }
          } // reader is disposed here
       } // command is disposed here
    } // connection is disposed here

    return result;
}

还有更多关于编码约定的内容。请参阅引用资料中的链接。

关于C# SqlCommand 命名约定,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32608713/

相关文章:

c# - Microsoft.VisualStudio.Profiler.dll 在哪里?

mysql - 比较 MySQL 中的日期

c# - 当 DB 值为 NULL 时将整数值显示为零的问题

jquery - 在 gridview 项目模板中,当 div 设置为不显示时,如何在鼠标悬停时显示/隐藏 div

c# - 如何更改 Asp.NET MVC 中的 Controller 命名约定?

c# - ServiceStack.Text 将字符串反序列化为单个对象空引用

c# - 如何避免 SynchronizationLockException?

c# - 浮点加法 : loss-of-precision issues

mysql - 为另一个 SELECT 选择列名 - 可能吗?

sql - Rails Active Record 相当于带有条件表达式的 SQL