How to determine if a string is a valid variable name?

后端 未结 5 415
执笔经年
执笔经年 2020-12-15 03:43

I\'m looking for a quick way (in C#) to determine if a string is a valid variable name. My first intuition is to whip up some regex to do it, but I\'m wondering if there\'s

5条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-15 04:43

    The longer way, plus it is much slower, is to use reflection to iterate over members of a class/namespace and compare by checking if the reflected member**.ToString()** is the same as the string input, this requires having the assembly loaded beforehand.

    Another way of doing it (a much longer way round it that overcomes the use of regex, by using an already available Antlr scanner/parser) borders on parsing/lexing C# code and then scanning for member names (i.e. variables) and comparing to the string used as an input, for example, input a string called 'fooBar', then specify the source (such as assembly or C# code) and scan it by analyzing looking specifically for declaration of members such as for example

    private int fooBar;
    

    Yes, it is complex but a powerful understanding will arise when you realize what compiler writers are doing and will enhance your knowledge of the C# language to a level where you get quite intimate with the syntax and its peculiarities.

提交回复
热议问题