C# 无需正则表达式验证类名格式和命名规范 (限制20个字节)
可以使用以下代码来判断自定义类名格式和C#命名规范是否一致且长度不超过20个字节,不使用正则表达式:
public static bool IsValidClassName(string className)
{
// 判断长度是否超过20个字节
if (className.Length > 20)
{
return false;
}
// 判断第一个字符是否为大写字母
if (!char.IsUpper(className[0]))
{
return false;
}
// 判断是否包含非法字符
foreach (char c in className)
{
if (!char.IsLetterOrDigit(c) && c != '_')
{
return false;
}
}
return true;
}
以下是该方法的使用示例:
string className = 'MyClass';
if (IsValidClassName(className))
{
// 类名格式正确,可以使用
}
else
{
// 类名格式不正确,需要修改
}
原文地址: https://www.cveoy.top/t/topic/lq2M 著作权归作者所有。请勿转载和采集!