相关疑难解决方法(0)

C#有办法给我一个不可变的字典吗?

核心C#库中是否有任何可以为我提供不可变字典的东西?

Java的一些东西:

Collections.unmodifiableMap(myMap);
Run Code Online (Sandbox Code Playgroud)

而且只是为了澄清,我不打算阻止键/值本身被改变,只是字典的结构.如果任何IDictionary的mutator方法被调用(Add, Remove, Clear),我想要快速和大声失败的东西.

.net c# java collections dictionary

68
推荐指数
3
解决办法
2万
查看次数

C#:Dictionary <K,V>如何在没有Add(KeyValuePair <K,V>)的情况下实现ICollection <KeyValuePair <K,V >>?

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'参数

为什么会这样?

.net c# dictionary interface

11
推荐指数
2
解决办法
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)

c# enums

11
推荐指数
1
解决办法
1万
查看次数

编译器会优化集合初始化?

编译器会优化此代码还是在每次调用方法后初始化集合?

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#中创建常量字典

.net c# dictionary compiler-optimization

8
推荐指数
2
解决办法
798
查看次数

C#,使用反射来获取switch中的每个案例名称

这是一个字符串文字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)

你明白了.

我喜欢做的是通过反射打印每个案例的每个字符串.

我没有做足够的反思,知道如何直观地做到这一点.老实说,我不确定反思是否可以做这种事情.

可以吗?如果是这样,怎么样?

.net c# reflection switch-statement

1
推荐指数
1
解决办法
943
查看次数