C# 类名验证:符合命名规范,驼峰命名法,字节限制
以下是一个示例代码,可以用来判断自定义类名是否符合 C# 命名规则:
public static bool IsCSharpClassNameValid(string className)
{
if (string.IsNullOrEmpty(className))
{
return false;
}
// 检查首字母是否为小写
if (!char.IsLower(className[0]))
{
return false;
}
// 检查是否存在无效字符
foreach (char c in className)
{
if (!char.IsLetterOrDigit(c) && c != '_')
{
return false;
}
}
// 检查长度是否超过 20 字节
if (System.Text.Encoding.UTF8.GetByteCount(className) > 20)
{
return false;
}
// 检查是否符合驼峰命名法
bool isUpper = false;
foreach (char c in className)
{
if (char.IsUpper(c))
{
if (isUpper)
{
return false;
}
isUpper = true;
}
else
{
isUpper = false;
}
}
return true;
}
该代码首先检查类名是否为空或 null,然后检查第一个字符是否为小写字母。接下来,它遍历类名中的每个字符,检查是否存在无效字符。如果类名长度大于 20 字节,则返回 false。最后,它检查类名是否符合驼峰命名法,并返回 true 或 false。
原文地址: https://www.cveoy.top/t/topic/lo28 著作权归作者所有。请勿转载和采集!