如果键声明为可为空,我们如何从字典中获取值

本文关键字:字典 获取 我们 声明 如果 | 更新日期: 2023-09-27 17:56:48

我有一个场景,其中属性被定义为 null able int,并且我有加载键和值的字典。我想通过给出一个可为 null 的 int 类型的键来获取值,如果键为 null 或字典中不存在键,则字典返回默认值。

这是一个例子

public partial class Form1 : Form
{
    Dictionary<int, string> students = new Dictionary<int, string>()
{
    { 111, "a"},
    { 112, "b"},
    { 113, "c"}
};
    public Form1()
    {
        InitializeComponent();
    }
    private void button1_Click(object sender, EventArgs e)
    {
        int? a;
        a = 111; //this value is coming from somewhere else and it can be null
        string student = students[a];
    }

}

如果我们定义 int? a; 作为 int a; 那么它不会给出错误。但我必须使 "a" 变量为 null able。请帮助我。

如果键声明为可为空,我们如何从字典中获取值

如何处理可为空的类型:

您需要Value属性:

string student = students[a.Value];

如果分配了一个值,则 Value 属性返回一个值。否则,一个 System.InvalidOperationException 被抛出。

或者将字典更改为具有可为空的键:

Dictionary<int?, string> students = new Dictionary<int?, string>()
{
     { 111, "a"},
     { 112, "b"},
     { 113, "c"}
};

或者,如果您需要检查Nullable变量是否有

string student = null;
if (a.HasValue)
    student = students[a.Value];
else
{
    // do something about it
}

如果变量包含值,则 HasValue 属性返回 true, 如果为空,则为 false。

要回答您的主要问题:

以上所有内容都是为了使您的代码使用 Nullable 类型进行编译,至于检查字典中是否存在值,您可以使用 TryGetValue 遵循此方法:

string student = null;
if(a.HasValue && students.TryGetValue(a.Value, out student))
{
    // key found and Value now stored in student variable
}
else
{
    // key not found, student is null
}

注意:以上假设字典仍定义为 Dictionary<int, string> 。这就是我们进行a.HasValue检查的原因。