c#中的文字哈希?

Dev*_*ris 30 c# ruby hashtable literals

我已经做了很长一段时间的c#,从来没有遇到过简单的新方法.

我最近熟悉哈希和奇迹的ruby语法,有没有人知道一种简单的方法来声明哈希作为文字,而不做所有的添加调用.

{ "whatever" => {i => 1}; "and then something else" => {j => 2}};
Run Code Online (Sandbox Code Playgroud)

Whe*_*lie 34

如果您使用的是C#3.0(.NET 3.5),则可以使用集合初始值设定项.它们不像Ruby那样简洁,但仍然是一种改进.

此示例基于MSDN示例

var students = new Dictionary<int, StudentName>()
{
    { 111, new StudentName {FirstName="Sachin", LastName="Karnik", ID=211}},
    { 112, new StudentName {FirstName="Dina", LastName="Salimzianova", ID=317, }},
    { 113, new StudentName {FirstName="Andy", LastName="Ruth", ID=198, }}
};
Run Code Online (Sandbox Code Playgroud)

  • BTW:VisualStudio/ReSharper告诉我,新Dictionary <int,StudentName>()中的括号是可选的和冗余的.保存两个字符;) (3认同)

Mat*_*att 7

当我无法使用C#3.0时,我使用一个帮助函数将一组参数转换为字典.

public IDictionary<KeyType, ValueType> Dict<KeyType, ValueType>(params object[] data)
{
    Dictionary<KeyType, ValueType> dict = new Dictionary<KeyType, ValueType>((data == null ? 0 :data.Length / 2));
    if (data == null || data.Length == 0) return dict;

    KeyType key = default(KeyType);
    ValueType value = default(ValueType);

    for (int i = 0; i < data.Length; i++)
    {
        if (i % 2 == 0)
            key = (KeyType) data[i];
        else
        {
            value = (ValueType) data[i];
            dict.Add(key, value);
        }
    }

    return dict;
}
Run Code Online (Sandbox Code Playgroud)

使用这样:

IDictionary<string,object> myDictionary = Dict<string,object>(
    "foo",    50,
    "bar",    100
);
Run Code Online (Sandbox Code Playgroud)