是否有一种编程方法来识别 .Net 保留字



>我正在寻找在VS 2015中以编程方式读取.Net,C#保留关键字。

我得到了在 [link][1] 中读取 C# 保留字的答案。

CSharpCodeProvider cs = new CSharpCodeProvider();
var test = cs.IsValidIdentifier("new"); // returns false
var test2 = cs.IsValidIdentifier("new1"); // returns true

但是对于vardynamicListDictionary等,上面的代码返回了错误的结果。

有没有办法在运行时识别 .net 关键字而不是在列表中列出关键字?

string[] _keywords = new[] { "List", "Dictionary" };

这是一个非常好的 C# 程序:

using System;
namespace ConsoleApplication6
{
    class Program
    {
        static void Main(string[] args)
        {
            int var = 7;
            string dynamic = "test";
            double List = 1.23;
            Console.WriteLine(var);
            Console.WriteLine(dynamic);
            Console.WriteLine(List);
        }
    }
}

所以你的前提错了。您可以通过在短列表中查找关键字来找到关键字。仅仅因为某物有意义并不意味着它以任何方式"保留"。

不要让在线语法突出显示混淆您。复制并粘贴到Visual Studio中,如果你想看到正确的突出显示。

正如 nvoigt 所解释的,以编程方式确定字符串是否为关键字的方法实际上是正确的。为了完成,(在检查反射器之后)它应该是:

bool IsKeyword(string s)
{
    var cscp = new CSharpCodeProvider();
    return s != null
           && CodeGenerator.IsValidLanguageIndependentIdentifier(s)
           && s.Length <= 512
           && !cscp.IsValidIdentifier(s);
}

(VB.NET 版本需要 1023 并检查"_"。

最新更新