C# 类名校验:判断是否符合命名规范(含汉字)
可以通过以下方式判断自定义类名是否符合 C# 命名规范:
-
首先判断类名的第一个字符是否为大写字母。
-
遍历类名的每个字符,如果存在字符不是大写字母、小写字母、数字、下划线或汉字,则认为类名不符合命名规范。
-
如果类名中包含汉字,则需要判断汉字是否符合规范。
下面是一个示例代码:
using System.Text.RegularExpressions;
public class ClassNameValidator
{
public static bool IsValid(string className)
{
if (string.IsNullOrEmpty(className) || !char.IsUpper(className[0]))
{
return false;
}
foreach (char c in className)
{
if (!char.IsLetterOrDigit(c) && c != '_' && !IsChineseChar(c))
{
return false;
}
}
return true;
}
private static bool IsChineseChar(char c)
{
Regex rx = new Regex('^[一-龥]$');
return rx.IsMatch(c.ToString());
}
}
使用示例:
string className1 = 'MyClass'; // 符合命名规范
string className2 = 'myClass'; // 不符合命名规范,首字母应该大写
string className3 = 'My_Class'; // 符合命名规范
string className4 = 'MyClass1'; // 符合命名规范
string className5 = 'MyClass_1'; // 符合命名规范
string className6 = 'MyClass中文'; // 符合命名规范,包含汉字
string className7 = 'MyClass中文1'; // 不符合命名规范,汉字后面不能跟数字
bool isValid1 = ClassNameValidator.IsValid(className1); // true
bool isValid2 = ClassNameValidator.IsValid(className2); // false
bool isValid3 = ClassNameValidator.IsValid(className3); // true
bool isValid4 = ClassNameValidator.IsValid(className4); // true
bool isValid5 = ClassNameValidator.IsValid(className5); // true
bool isValid6 = ClassNameValidator.IsValid(className6); // true
bool isValid7 = ClassNameValidator.IsValid(className7); // false
原文地址: https://www.cveoy.top/t/topic/lpAE 著作权归作者所有。请勿转载和采集!