核心C#库中是否有任何可以为我提供不可变字典的东西?
Java的一些东西:
Collections.unmodifiableMap(myMap);
Run Code Online (Sandbox Code Playgroud)
而且只是为了澄清,我不打算阻止键/值本身被改变,只是字典的结构.如果任何IDictionary的mutator方法被调用(Add, Remove, Clear
),我想要快速和大声失败的东西.
看System.Collections.Generic.Dictionary<TKey, TValue>
,它清楚地实现ICollection<KeyValuePair<TKey, TValue>>
,但没有所需的" void Add(KeyValuePair<TKey, TValue> item)
"功能.
尝试初始化时也可以看到Dictionary
这样:
private const Dictionary<string, int> PropertyIDs = new Dictionary<string, int>()
{
new KeyValuePair<string,int>("muh", 2)
};
Run Code Online (Sandbox Code Playgroud)
失败了
方法'Add'没有重载需要'1'参数
为什么会这样?
我是C#的新手,我在枚举方面遇到了一些麻烦.
我有Enum定义如下:
public enum CustomFields
{
[Display(Name = "first_name")]
FirstName = 1,
[Display(Name = "last_name")]
LastName = 2,
}
Run Code Online (Sandbox Code Playgroud)
我需要的是将检查显示名称是否存在的代码,如果是,则返回枚举值.
如果我有显示名称:
var name = "first_name";
Run Code Online (Sandbox Code Playgroud)
我需要这样的东西:
var name = "first_name";
CustomFields.getEnumValue(name);
Run Code Online (Sandbox Code Playgroud)
这应该返回:
CustomFields.FirstName;
Run Code Online (Sandbox Code Playgroud) 编译器会优化此代码还是在每次调用方法后初始化集合?
private string Parse(string s)
{
var dict = new Dictionary<string, string>
{
{"a", "x"},
{"b", "y"}
};
return dict[s];
}
Run Code Online (Sandbox Code Playgroud)
如果答案是否定的,我建议使用此解决方案:在C#中创建常量字典
这是一个字符串文字switch语句的人为例子:
static string GetStuff(string key)
{
switch (key)
{
case "thing1": return "oh no";
case "thing2": return "oh yes";
case "cat": return "in a hat";
case "wocket": return "in my pocket";
case "redFish": return "blue fish";
case "oneFish": return "two fish";
default: throw new NotImplementedException("The key '" + key + "' does not exist, go ask your Dad");
}
}
Run Code Online (Sandbox Code Playgroud)
你明白了.
我喜欢做的是通过反射打印每个案例的每个字符串.
我没有做足够的反思,知道如何直观地做到这一点.老实说,我不确定反思是否可以做这种事情.
可以吗?如果是这样,怎么样?