什么是C#数组的命名约定?

问题描述 投票:-3回答:2
string[] Names = {};
string[] names = {};

使用大写字母更好吗?数组和其他类型的约定是否相同?

c#
2个回答
4
投票

您会在C#示例和.NET框架命名中注意到,通常所有内容都是camelCase

  • 所有变量应具有lowercaseCamelCase名称。
  • 所有类型classstructenumdelegate),方法属性应具有UppercaseCamelCase(又名PascalCase)名称。

这里是一个例子:

// Types are CamelCase
class Foo {

    // Properies are PascalCase
    public int SomeProperty { get; set; }

    // *Private* fields are lowerCamelCase
    private int aField;

    // By some conventions (I use these)
    private int m_anotherField;            // "m_" for "member"
    private static object s_staticLock;    // "s_" for "static"

    // *Public* fields are PascalCase
    public int DontUsePublicFields;        // In general, don't use these
    public const int ConstantNumber = 42;

    // Methods are UpperCase
    // Parameters and variables are lowerCase
    public SomeMethod(int myParameter) {
        int[] localVariable;

        //string names[] = {};     // Not valid C#! 
        string[] names = new string[] { "Jack", "Jill" };
    }
}

另请参见:


1
投票

所有这些都有效吗?使用大写字母更好吗?

最后一个(string names[] = {};)无效的C#。就语法而言,其他两个是正确的。

建议变量的大写字母取决于用法。方法的局部变量或参数通常以小写字母(技术上为camelCase)命名,字段属性为大写(技术上为PascalCase)。有关详细信息,请参见Capitalization Conventions

请注意,这些约定与变量的类型无关,而是它的用法。您正在处理数组的事实不必更改变量的名称-至少不更改变量名称的大写字母。 (但是,您可能希望使用一个名称来表明变量是某种形式的“集合”。)

话虽这么说,这纯粹是一个约定,而使用的命名完全取决于您。

如果最好使用大写字母,是否意味着将数组视为对象?

大小写与变量的处理方式无关,仅与变量的类型有关。更改大小写可能会向其他开发人员暗示类型是字段或属性,但是从语言或用法的角度来看,它实际上并未以任何方式更改变量。

© www.soinside.com 2019 - 2024. All rights reserved.