Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่า String เป็น Keyword ของ C# หรือไม่

ภาพรวม

ใช้ CodeDomProvider.IsValidIdentifier ตรวจสอบว่าสตริงเป็น identifier ที่ถูกต้องใน C# หรือไม่ ถ้าไม่ใช่ identifier ที่ถูกต้อง อาจเป็น keyword (แต่ไม่ครอบคลุมทุกกรณี)

โค้ดตัวอย่าง


using System;
using System.CodeDom.Compiler;

namespace Program {
    class Demo {
        static void Main(string[] args) {
            string str1 = "amit";
            string str2 = "for";

            CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");

            CheckIdentifier(provider, str1);
            CheckIdentifier(provider, str2);
        }

        static void CheckIdentifier(CodeDomProvider provider, string str) {
            if (provider.IsValidIdentifier(str)) {
                Console.WriteLine($"{str} is a valid identifier");
            } else {
                Console.WriteLine($"{str} is a C# keyword or invalid identifier");
            }
        }
    }
}

ผลลัพธ์


amit is a valid identifier
for is a C# keyword or invalid identifier

ข้อจำกัด

  • IsValidIdentifier คืนค่า false สำหรับ keyword แต่คืนค่า false สำหรับ identifier ที่ไม่ถูกต้องด้วย (เช่น เริ่มต้นด้วยตัวเลข, มี space, สัญลักษณ์พิเศษ)
  • ไม่สามารถแยกแยะได้ว่าเป็น keyword จริงหรือแค่ identifier ผิดรูปแบบ

วิธีที่แม่นยำกว่า: รายการ Keyword ทั้งหมด


using System;
using System.Collections.Generic;

public class KeywordChecker {
    private static readonly HashSet<string> _keywords = new HashSet<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", "add", "alias", "ascending", "async",
        "await", "by", "descending", "dynamic", "equals", "from",
        "get", "global", "group", "into", "join", "let", "nameof",
        "on", "orderby", "partial", "remove", "select", "set",
        "value", "var", "when", "where", "yield"
    };

    public static bool IsKeyword(string word) => _keywords.Contains(word);

    public static void Main() {
        Console.WriteLine(IsKeyword("for"));    // True
        Console.WriteLine(IsKeyword("while"));  // True
        Console.WriteLine(IsKeyword("amit"));   // False
        Console.WriteLine(IsKeyword("123abc")); // False (invalid identifier)
    }
}

Contextual Keywords

บางคำเป็น keyword เฉพาะในบริบทบางอย่าง (contextual keywords) เช่น var, async, await, yield, nameof - สามารถใช้เป็น identifier ได้ในบริบทอื่น