Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C#返回字典查找的结果,如果为NULL,则返回其他内容_C# - Fatal编程技术网

C#返回字典查找的结果,如果为NULL,则返回其他内容

C#返回字典查找的结果,如果为NULL,则返回其他内容,c#,C#,这是我当前的功能(它可以工作,但不知道是否有更干净的方法来实现) publicstaticdictionary profileNetworkLowCostPriorityList; 公共静态双determineneWorksortOrderValue(int网络,双倍费用) { 如果(profileNetworkLowCostPriorityList==null)返回费用; 如果(profileNetworkLowCostPriorityList[network]!=null)返回profile

这是我当前的功能(它可以工作,但不知道是否有更干净的方法来实现)

publicstaticdictionary profileNetworkLowCostPriorityList;
公共静态双determineneWorksortOrderValue(int网络,双倍费用)
{
如果(profileNetworkLowCostPriorityList==null)返回费用;

如果(profileNetworkLowCostPriorityList[network]!=null)返回profileNetworkLowCostPriorityList[network]; 退货费; }
基本上,如果
dictional
对象不为空,并且在dictional中找到了某个内容,则返回该内容。如果没有,请返回其他内容。我关心的是引用空字典对象和抛出错误。我当然可以捕捉错误并返回一些东西,但不确定这是否是最好的方法


对于我们处理的每个“小部件”,此代码将运行数亿次,因此我们正在寻找一种“有效的方法”来执行此操作。

听起来您只是想要
TryGetValue
,基本上:

public static double DetermineNetworkSortOrderValue(int network, double fee)
{
    double dictionaryFee;
    return profileNetworkLowCostPriorityList == null ||
        !profileNetworkLowCostPriorityList.TryGetValue(network, out dictionaryFee)
        ? fee : dictionaryFee;
}
还请注意,您当前的代码目前不起作用-如果网络没有字典条目,将引发异常。您还应该看到这样的编译时警告:

表达式的结果始终为“true”,因为“double”类型的值永远不等于“double”类型的“null”


不要忽视这样的警告。我还强烈建议您不要公开公共字段…

返回profileNetworkLowCostPriorityList!=无效的(profileNetworkLowCostPriorityList[网络]??费用):费用;“注意:
词典
不想在预标记中使用”-请阅读有关如何格式化代码的格式化提示。只需将整个块缩进四个空格,而不用
。谢谢您的帮助。TryGetValue正是我想要的。我不知道。在公开公共字段时,您的意思是将
profileNetworkLowCostPriorityList
设为私有,并在其上编写getter和setter方法吗?@thomas:嗯,您可以公开一个属性,但我想您最好仔细考虑实际需要在其上公开哪些操作。数据来自哪里?您能否单独加载它,然后有效地将其用作只读数据源?我们没有上下文来告诉您如何修复它,但是公共字段几乎总是一个坏主意,而公共静态字段更是如此。(“这是一个全球性的国家——你想用它做什么就用它做什么!”
public static double DetermineNetworkSortOrderValue(int network, double fee)
{
    double dictionaryFee;
    return profileNetworkLowCostPriorityList == null ||
        !profileNetworkLowCostPriorityList.TryGetValue(network, out dictionaryFee)
        ? fee : dictionaryFee;
}