为什么可以为空的KeyValuePair <,>没有关键属性?

Mat*_*att 12 .net c# generics .net-2.0

我有以下内容:

KeyValuePair<string, string>? myKVP;
// code that may conditionally do something with it
string keyString = myKVP.Key;  
// throws 'System.Nullable<System.Collections.Generic.KeyValuePair<string,string>>' 
// does not contain a definition for 'Key'
Run Code Online (Sandbox Code Playgroud)

我确信这有一些原因,因为我可以看到该类型可以为空.是因为我试图在null可能导致坏事发生时访问密钥?

And*_*are 22

试试这个:

myKVP.Value.Key;
Run Code Online (Sandbox Code Playgroud)

这是一个精简版System.Nullable<T>:

public struct Nullable<T> where T: struct
{
    public T Value { get; }
}
Run Code Online (Sandbox Code Playgroud)

由于Value属性是类型T,因此必须使用该Value属性来获取正在使用的包装类型实例.

编辑:我建议您HasValue在使用之前检查可空类型的属性Value.

if (myKVP.HasValue)
{
    // use myKVP.Value in here safely
}
Run Code Online (Sandbox Code Playgroud)