using System.Text.RegularExpressions;
namespace Mx.Utils
{
/// <summary>
/// Unity命名验证工具类
/// </summary>
public class UnityNamingValidator
{
/// <summary>
/// 验证变量名是否符合Unity的命名规范
/// </summary>
/// <param name="name">要验证的变量名</param>
/// <returns>如果变量名有效则返回true,否则返回false</returns>
public static bool IsValidVariableName(string name)
{
string pattern = @"^([a-zA-Z_][a-zA-Z0-9_]*)$";
if (Regex.IsMatch(name, pattern))
return !IsKeyword(name);
return false;
}
/// <summary>
/// 检查名字是否是C#的保留字
/// </summary>
/// <param name="word">要检查的单词</param>
/// <returns>如果是C#的保留字则返回true,否则返回false</returns>
private static bool IsKeyword(string word)
{
string[] keywords = 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"
};
foreach (string keyword in keywords)
{
if (word == keyword)
return true;
}
return false;
}
}
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
- 12.
- 13.
- 14.
- 15.
- 16.
- 17.
- 18.
- 19.
- 20.
- 21.
- 22.
- 23.
- 24.
- 25.
- 26.
- 27.
- 28.
- 29.
- 30.
- 31.
- 32.
- 33.
- 34.
- 35.
- 36.
- 37.
- 38.
- 39.
- 40.
- 41.
- 42.
- 43.
- 44.
- 45.
- 46.
- 47.
- 48.
- 49.
- 50.
- 51.
- 52.
- 53.