代码之家  ›  专栏  ›  技术社区  ›  Benjamin Caure

Razor标记中可为null的参数出现编译错误

  •  0
  • Benjamin Caure  · 技术社区  · 2 年前

    我声明了一个带有可选参数的Razor页面:

    [Parameter]
    public KeyValuePair<string, T>? Value { get; set; }
    

    我在Razor页面标记中使用:

    @if (Value != null && item.Key == Value.Key)
    {
        <span>
           .....
        </span>
    }
    

    Visual Studio抱怨使用“?”声明的可为null的类型(如果我删除“?”,则没有错误):

    CS1061  'KeyValuePair<string, T>?' does not contain a definition for 'Key' and no accessible extension method 'Key' accepting a first argument of type 'KeyValuePair<string, T>?'
    

    它似乎忽略了我的“Value!=null”测试。修复此错误的“Blazor”方法是什么?

    1 回复  |  直到 2 年前
        1
  •  2
  •   Henk Holterman    2 年前

    KeyValuePair<K,V> 是一个valuetype(结构)。

    当您使用可为null的valuetype时,您将不得不处理Value属性:

    public KeyValuePair<string, T>? Value { get; set; } 
    
    
       @if (Value != null && item.Key == Value.Value.Key)