c# - 实例化之后是赋值编译,但是

标签 c# generics dictionary reference

我想允许用户在搜索鸭嘴兽时输入鸭嘴兽的 ID 或名称(或名称的一部分)。

数据库现在已关闭,所以我无法测试这段代码,但我两次分配给 kvp 的事实似乎并不正确。无论如何,首先是我的代码:

String SearchVal = textBoxPlatypusNumOrPartialName.Text.Trim();
int PlatypusID;
int.TryParse(SearchVal, out PlatypusID);

Dictionary<int, string> CandidatePlatypusDict = PlatypusID > 0 ? PlatypusSetupData.GetPlatypusById(PlatypusID) :        PlatypusSetupData.GetCandidatePlatypusFromName(SearchVal);

KeyValuePair<int, String> kvp = new KeyValuePair<int, string>();
using (var getPlatypusIDAndNameDlg = new GetPlatypusForm(CandidatePlatypusDict)) {
    DialogResult dr = getPlatypusIDAndNameDlg.ShowDialog();
    if (dr == DialogResult.OK) {
        kvp = getPlatypusIDAndNameDlg.PlatypusKVP; 
    }
}

...现在,如果我尝试这样做:

KeyValuePair<int, String> kvp; // = new KeyValuePair<int, string>();

我得到:“使用未分配的局部变量‘kvp’”

而且我不能将 null 分配为 KeyValuePair,因为它是不可为 null 的类型。

这个 kvp 的实例化之后是赋值给它是否可以,如果不是,我该如何解决它?

最佳答案

Is this instantiation of kvp followed by assignment to it okay, and if not, how can I work around it?

好吧,没关系 - 但您可能想要:

KeyValuePair<int, String> kvp;
using (...) {
   kvp = dr == DialogResult.OK ? getPlatypusIDAndNameDlg.PlatypusKVP 
                               : /* some other value here */;
}

这样它显然只被分配一次,但总是被分配。接下来,您需要确定在 dr 不是 DialogResult.OK 的情况下您希望它具有什么值。

关于c# - 实例化之后是赋值编译,但是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11399871/

相关文章:

c# - 如何查看类型参数的实际运行类型?

python - 如何在 Python 中对列表中的单词进行编码

python - 如何在一行中将列表转换为索引和数据的字典(用于lambda)

javascript - 如何在 Phaser 中的 mapLayer 上获取平铺类型

c# - 是否可以首先在 Entity Framework 代码中使用 PK 列作为鉴别器?

javascript - 使用 ajax 调用异步 web api 方法

c# - 降低绑定(bind)DataGrid的刷新率

C# 定时器回调在每个循环中使用函数的返回值

c# - 动态查询 SQL Server

java - 将 .getClass() 转换为类型参数