我想string在C#中的变量名中包含一些特殊字符.
示例: string foo-bar = String.Empty;
据我所知,我不能像上面的例子中提到的那样声明变量.是否有办法声明包含" - "的变量名称?
不,这在 C# 中是不可能的。
如果你真的,真的,真的想要这样做,你可以使用Dictionary<string, string>:
Dictionary<string, string> someVars = new Dictionary<string, string>()
{
{"foo-bar", String.Empty},
{"bar-foo", "bazinga"}
}
Run Code Online (Sandbox Code Playgroud)
使用它们看起来像这样:
string newstring = someVars["foo-bar"] + "Hello World!";
Run Code Online (Sandbox Code Playgroud)
您不仅可以使用变量名,还可以在字典中查找字符串。请注意,这是非常低效的,只是一个玩笑,所以请不要真正使用它;)