[英]C# SqlCommand naming convention
我对使用 C# 和 ASP.NET 还很陌生,我很好奇在 SQL 数据库上运行多个查询时是否有命名 SqlCommands 的约定。 例如,我已经创建了我的 SqlConnection 并且我希望调用一个函数、两个存储过程,并且只创建一个常规的简单查询。 目前,我正在使用:
SqlCommand function = new SqlCommand();
SqlCommand command = new SqlCommand();
SqlCommand proc1 = new SqlCommand();
SqlCommand proc2 = new SqlCommand();
对于这些不同的命令是否有更可接受的命名约定,或者我应该只使用单个命令,因为我在后面的代码块中使用 CommandText 和 CommandType 调用?
如果您在同一范围内有很多命令,您可以使用类似personCommand
或productCommand
名称。 从MSDN 通用命名约定,您可以:
请选择易于阅读的标识符名称。 例如,名为 HorizontalAlignment 的属性比 AlignmentHorizontal 更易读英文。
一定要重视可读性而不是简洁。 属性名称 CanScrollHorizontally 优于 ScrollableX(对 X 轴的模糊引用)。
请勿使用下划线、连字符或任何其他非字母数字字符。 X 不要使用匈牙利符号。
避免使用与广泛使用的编程语言的关键字冲突的标识符。
请参阅有关C# 编码约定的更多信息。 在其他情况下,我更喜欢只使用command
来保持简单,因为范围会告诉我。
另一个很好的提示,当您使用实现IDisposable
接口(如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;
}
还有更多关于编码约定的内容。 请参阅参考资料中的链接。
一个好的和更易读的约定是表达命令将做什么。 如果您阅读updateProductCommand或queryCategoryCommand,每个人都会立即知道该命令的用途。 当您以存储过程为目标时,最好使用 sproc 名称作为命令前缀,如sp_UpdateProductCommand 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.