【问题标题】:Nullable<T> for generic method in c#?c# 中泛型方法的 Nullable<T>?
【发布时间】:2010-12-20 19:18:40
【问题描述】:

如何编写一个可以将 Nullable 对象用作扩展方法的通用方法。我想将 XElement 添加到父元素,但前提是要使用的值不为 null。

例如

public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T childValue){
...
code to check if value is null
add element to parent here if not null
...
}

如果我做这个AddOptionalElement&lt;T?&gt;(...),那么我会得到编译器错误。 如果我做这个AddOptionalElement&lt;Nullable&lt;T&gt;&gt;(...),那么我会得到编译器错误。

有什么方法可以实现吗?

我知道我可以调用该方法:

parent.AddOptionalElement<MyType?>(...)

但这是唯一的方法吗?

【问题讨论】:

    标签: c# generics nullable


    【解决方案1】:
    public static XElement AddOptionalElement<T>(
        this XElement parentElement, string childname, T? childValue)
        where T : struct
    {
        // ...
    }
    

    【讨论】:

    • 类型“T”必须是不可为空的值类型才能在泛型类型或方法“System.Nullable”中用作参数“T”
    • 它仍然会出现编译器错误,因为我们需要指出 T 需要不可为空。
    • @BlueChippy:正如你评论的那样正在修复它!
    • 谢谢 LukeH:最后一个问题?枚举是结构吗?
    • @BlueChippy:是的,枚举是值类型,所以struct 约束允许它们。
    【解决方案2】:

    您需要将T 限制为struct - 否则它不能为空。

    public static XElement AddOptionalElement<T>(this XElement parentElement, 
                                                 string childname, 
                                                 T? childValue) where T: struct { ... }
    

    【讨论】:

    • 它不是需要为空的“this”,而是其他参数之一。例如MethodName(此 XElement 父级,“NeedANullableHere”值)
    • 已编辑...您的“将 Nullable 对象用作扩展方法”有点令人困惑。
    【解决方案3】:

    试试
    AddOptionalElement&lt;T&gt;(T? param) where T: struct { ... }

    【讨论】:

      【解决方案4】:

      The Nullable 类型具有约束 where T : struct, new() 因此您的方法显然应该包含 struct 约束以使 Nullable&lt;T&gt; 正常工作。生成的方法应如下所示:

      public static XElement AddOptionalElement<T>(this XElement parentElement, string childname, T? childValue) where T : struct
          {
            // TODO: your implementation here
          }
      

      【讨论】:

      • struct 暗示new() 为约束,无需显式添加。
      猜你喜欢
      • 1970-01-01
      • 2017-02-12
      • 1970-01-01
      • 1970-01-01
      • 2023-03-31
      • 1970-01-01
      • 2022-12-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多