C# 中 "var" 的命名约定

Naming Convention for "var" in C#

如何使用 var 类型正确初始化 class?我经常看到这个版本:

var converter = new Converter();

classes 的实例应该用 PascalCase 编写,对吧?为什么 var 不同?

我认为您误解了 var 的含义,并且混淆了 class、引用和 var(以及每个变量的命名约定)。

那么 var 是什么? From docs:

variables that are declared at method scope can have an implicit "type" var. An implicitly typed local variable is strongly typed just as if you had declared the type yourself, but the compiler determines the type

来自 Implicitly Typed Local Variables:

The var keyword instructs the compiler to infer the type of the variable from the expression on the right side of the initialization statement

所以在这种情况下 var converter = new Converter();:

  • 编译器将 var 确定为 Converter
  • 您正在创建一个名为 converter 的引用 - 应该使用驼峰命名。
  • 引用的显式类型是 Converter - ,应该使用 PascalCasing 命名。

var converter = new Converter();等同于写Converter converter = new Converter();


在 C# 中,var 适用于您不知道显式类型(例如匿名类型)的情况,或者作为一种简单的编写方式:

Dictionary<SomeTpye, List<SomeOtherType<AndSomeGenericParameter>> variable = 
    new Dictionary<SomeTpye, List<SomeOtherType<AndSomeGenericParameter>>();

像这样:

var variable = new Dictionary<SomeTpye, List<SomeOtherType<AndSomeGenericParameter>>();

因为它是类型的 "alias" 而不是类型本身,所以它遵守语言关键字(而不是类型)的约定,并以小写形式书写。