1

我对 C# 还是有点陌生​​……我发现自己一遍又一遍地重用一个特定的过程。在我为个人懒惰写一个辅助方法之前,有没有更短或更错误的方法来写这种语句?

Dictionary<string, string> data = someBigDictionary;
string createdBy;
data.TryGetValue("CreatedBy", out createdBy);
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = createdBy ?? "Unknown",
    //set 15 other values
    ...
}

本质上,通过尝试获取值来设置对象的属性,然后如果它为空,则使用默认值。我有很多属性,如果我可以就更好了

MyEntity me = new MyEntity{
    CreatedBy = TryToGetValueOrReturnNull(data, "CreatedBy") ?? "Unknown",
    ...
}

同样,我完全有能力编写自己的辅助函数。在此之前,我正在寻找现有的本机功能或速记。

4

3 回答 3

5

There are many similar questions (like this and this) which propose different solutions from extension methods to inheriting from dictionary and overriding indexer. However they are written before C# 7, and with C# 7 you can do this in one line:

CreatedBy = data.TryGetValue("CreatedBy", out var value) ? value : "Unknown"
于 2017-06-06T13:04:58.970 回答
3
public static class DictionaryExtensions
{
    public static U TryGetValueOrDefault<T, U>(this IDictionary<T, U> dict, T key, U defaultValue)
    {
        U temp;

        if (dict.TryGetValue(key, out temp))
            return temp;

        return defaultValue;
    }
}

然后做类似的事情:

Dictionary<string, string> data = someBigDictionary;
//do that for 15 other values
...
MyEntity me = new MyEntity{
    CreatedBy = data.TryGetValueOrDefault("CreatedBy", "Unknown"),
    //set 15 other values
    ...
}
于 2017-06-06T12:58:54.927 回答
1

TryGetValue返回一个bool指示是否在字典中找到键。因此,如果找不到,您应该使用它并将变量设置为默认值:

string createdBy;
if (!data.TryGetValue("CreatedBy", out createdBy)) createdBy="Unknown";
于 2017-06-06T13:01:56.103 回答