gpt4 book ai didi

c# - 可空泛型扩展方法

转载 作者:行者123 更新时间:2023-12-04 01:02:27 25 4
gpt4 key购买 nike

我想编写一个通用扩展方法,如果没有值则抛出错误。所以我想要这样的东西:

public static T GetValueOrThrow(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}

return candidate.Value;
}
  1. C# 无法识别 T:找不到类型或 namespace 名称“T”
  2. C# 无法识别 where : Constraints are not allowed on non generic declarations

知道这是否有效吗?我错过了什么?

我还想出了:

public static T GetValueOrThrow<T>(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}

return candidate.Value;
}

现在 C# 提示候选人:类型 T 必须是不可空值类型才能将其用作泛型类型或方法 Nullable 中的参数 T

这与比较无关。

最佳答案

public static T GetValueOrThrow<T>(this Nullable<T> candidate) where T : struct // can be this T? as well, but I think with explicit type is easier to understand
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}

where T : class 限制为引用类型,可以为 null,但 HasValue 是 Nullable type 的属性(这是值类型以及 T)。

关于c# - 可空泛型扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58013686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com