我对使用 C# 和 ASP.NET 还很陌生,我很好奇在 SQL 数据库上运行多个查询时是否有命名 SqlCommand 的约定。例如,我已经创建了我的 SqlConnection,我希望调用一个函数、两个存储过程,然后只创建一个常规的简单查询。目前,我正在使用:
SqlCommand function = new SqlCommand();
SqlCommand command = new SqlCommand();
SqlCommand proc1 = new SqlCommand();
SqlCommand proc2 = new SqlCommand();
对于这些不同的命令是否有更可接受的命名约定,或者我应该只使用一个命令,因为我在后面的代码块中使用 CommandText 和 CommandType 调用?
最佳答案
如果您在同一范围内有很多命令,您可以使用 personCommand
或 productCommand
这样的名称。来自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)的类型(如SqlCommand
、SqlConnection
)时,您可以使用 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/