更少错误TryGetValue然后null检查语法

时间:2017-06-06 12:53:24

标签: c# null-coalescing-operator trygetvalue

我对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
    ...
}

本质上,通过尝试获取值来设置对象的属性,然后如果它为null则使用默认值。我有很多属性,如果我能

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

同样,我完全有能力编写自己的帮助函数。在我这样做之前,我正在寻找现有的本机功能或简写。

3 个答案:

答案 0 :(得分:5)

有许多类似的问题(如thisthis)提出了从扩展方法到继承字典和覆盖索引器的不同解决方案。然而,它们是在C#7之前编写的,而在C#7中,您可以在一行中编写:

CreatedBy = data.TryGetValue("CreatedBy", out var value) ? value : "Unknown"

答案 1 :(得分: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
    ...
}

答案 2 :(得分:1)

TryGetValue返回bool,表示是否在字典中找到了密钥。因此,您应该使用它并将变量设置为默认值(如果未找到):

string createdBy;
if (!data.TryGetValue("CreatedBy", out createdBy)) createdBy="Unknown";