作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我想编写一个通用扩展方法,如果没有值则抛出错误。所以我想要这样的东西:
public static T GetValueOrThrow(this T? candidate) where T : class
{
if (candidate.HasValue == false)
{
throw new ArgumentNullException(nameof(candidate));
}
return candidate.Value;
}
知道这是否有效吗?我错过了什么?
我还想出了:
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/
我是一名优秀的程序员,十分优秀!