以下是判断自定义类名是否符合C#命名规则的示例代码:

public static bool IsValidClassName(string className)
{
    // 类名长度不超过20
    if (className.Length > 20)
    {
        return false;
    }
    // 类名首字母只能为大写字母或下划线
    if (!char.IsUpper(className[0]) && className[0] != '_')
    {
        return false;
    }
    // 类名只能由大写字母、小写字母、数字和下划线组成
    for (int i = 1; i < className.Length; i++)
    {
        if (!char.IsLetterOrDigit(className[i]) && className[i] != '_')
        {
            return false;
        }
    }
    // 类名不能与C#关键字重复
    if (new string[] { "abstract", "as", "base", "bool", "break", "byte", "case",
        "catch", "char", "checked", "class", "const", "continue", "decimal", "default",
        "delegate", "do", "double", "else", "enum", "event", "explicit", "extern", "false",
        "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in",
        "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null",
        "object", "operator", "out", "override", "params", "private", "protected", "public",
        "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc",
        "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof",
        "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "virtual", "void", "volatile",
        "while" }.Contains(className))
    {
        return false;
    }
    // 类名符合C#命名规则
    return true;
}

C# 命名规则:

  • 命名类型和结构时:
    • 使用Pascal命名规范(首字母大写)。
    • 使用名词或名词短语命名。
    • 请勿添加前缀(如:C++中在类名前加'C')。
  • 命名接口时:
    • 建议使用形容词短语(如:IDisposal)。
    • 请务必在接口名称前加上字母'I',表示该类型是一个接口。
  • 首字母: 只能用大写字母和下划线。
  • 字节不超过20: 类名长度不超过20个字符。
  • 字符: 只能由大写字母、小写字母、数字和下划线组成。
  • 关键字: 不能与C#关键字重复。
C# 类名命名规范验证 - 代码示例

原文地址: https://www.cveoy.top/t/topic/loZL 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录