我试图找到一种列出所有C#关键字的方法。我需要进行比较,例如:
{{1}}
通过搜索这些关键字的列表来做这件事会更好,我想在不输入的情况下这样做。
我正在查看System.CodeDom命名空间,看看能否找到一些东西。
如果你们中的任何一个人能告诉我在哪里可以找到它,我会非常感激。 提前谢谢!
答案 0 :(得分:12)
您可以使用
(?:^|\s)([-+]?(?:[0-9]*\.[0-9]+|[0-9]+))(?=$|\s)
using Microsoft.CSharp;
然后,您可以使用
CSharpCodeProvider cs = new CSharpCodeProvider();
答案 1 :(得分:1)
您可以在文档中找到所有关键字的列表:https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/index
new string[]
{
"bool", "byte", "sbyte", "short", "ushort", "int", "uint", "long", "ulong", "double", "float", "decimal",
"string", "char", "void", "object", "typeof", "sizeof", "null", "true", "false", "if", "else", "while", "for", "foreach", "do", "switch",
"case", "default", "lock", "try", "throw", "catch", "finally", "goto", "break", "continue", "return", "public", "private", "internal",
"protected", "static", "readonly", "sealed", "const", "fixed", "stackalloc", "volatile", "new", "override", "abstract", "virtual",
"event", "extern", "ref", "out", "in", "is", "as", "params", "__arglist", "__makeref", "__reftype", "__refvalue", "this", "base",
"namespace", "using", "class", "struct", "interface", "enum", "delegate", "checked", "unchecked", "unsafe", "operator", "implicit", "explicit"
};
答案 2 :(得分:1)
CSharpCodeProvider
有逻辑做到这一点。但你必须用反射来称呼它。它包含IsKeyword
函数。更具体地说,它具有IsKeyword
使用的实际关键字列表。
private static readonly string[][] keywords
答案 3 :(得分:0)
如果您不介意使用反射并依赖实现细节,则可以使用https://developer.apple.com/documentation/foundation/timer的静态IsKeyWord
方法。
using System;
using System.CodeDom.Compiler;
using Microsoft.CSharp;
using System.Reflection;
internal class CS
{
private static MethodInfo methIsKeyword;
static CS()
{
using (CSharpCodeProvider cs = new CSharpCodeProvider())
{
FieldInfo infoGenerator = cs.GetType().GetField("generator", BindingFlags.Instance | BindingFlags.NonPublic);
object gen = infoGenerator.GetValue(cs);
methIsKeyword = gen.GetType().GetMethod("IsKeyword", BindingFlags.Static | BindingFlags.NonPublic);
}
}
public static bool IsKeyword(string input)
{
return Convert.ToBoolean(methIsKeyword.Invoke(null, new object[] { input.Trim() }));
}
}
使用示例:
bool isKeyword = CS.IsKeyword("if");
答案 4 :(得分:0)
感谢Roslyn,您可以使用Microsoft.CodeAnalysis.CSharp nuget包来完成此操作。
添加此软件包后,您的代码将变为:
using Microsoft.CodeAnalysis.CSharp;
if (SyntaxFacts.GetKeywordKind(key) != SyntaxKind.None || SyntaxFacts.GetContextualKeywordKind(key) != SyntaxKind.None)
{
// do something
}
如果您需要尽快,请使用静态字段,例如:
private static readonly HashSet<string> Keywords =
SyntaxFacts.GetKeywordKinds().Select(SyntaxFacts.GetText).ToHashSet();
然后,您的代码变为:
if (Keywords.Contains(key))
{
// do something
}