检查字符串是否是编译时已知的文字字符串?

Saf*_*nes 6 c# string

我正在写一个库,我有一个接受字典的方法.字典的值是不受信任/不安全的,但密钥是可信的,如果最终用户能够输入任意密钥名称,则可能发生"坏事".

因此,当其他开发人员使用此库函数时,我想强制他们在编译时知道密钥名称.所以这样的事情是允许的:

string userInput = Console.ReadLine(); 
Dictionary<string, string> something = new Dictionary<string, string>();   
something.Add("MyKey", userInput);    
Run Code Online (Sandbox Code Playgroud)

因为"MyKey"是一个字符串文字,在编译时就知道了.但是这样的事情会引发编译或运行时异常:

string userInput = Console.ReadLine();
string userKey = Console.ReadLine(); 
Dictionary<string, string> something = new Dictionary<string, string>();   
something.Add(userKey, userInput);    
Run Code Online (Sandbox Code Playgroud)

因为用户输入用于密钥(userKey),因此在编译时它是未知的.

我查看了GetType(),并没有什么能真正区分文字字符串和运行时创建的字符串.

The*_*kis 2

我可以想到两种可能的方法,都使用反射:


值得一提的是,两者都可能被客户端代码伪造。例如,可以使用动态程序集System.ComponentModel.TypeDescriptor类。