c# - 如果 struct 不可为空,则在 C# 中检查 struct 是否为 null

标签 c# .net c#-4.0

我有一些通用的方法

T SomeMethod(Func<T> func){
   T result = func();
     if (result != null)
       { //.....}
}

如果 T 是类,它会很好地工作。但是T是struct怎么办?如果 Tstruct,我如何检查 result == default(T)

附言我不想使用约束 where T: classNullable 类型。

最佳答案

执行此操作的更惯用的方法是遵循 int.TryParse 之类的方法。

public delegate bool TryFunction<T>(out T result);

T SomeMethod(TryFunction<T> func)
{
    T value;

    if(func(out value))
    {

    }
}

关于c# - 如果 struct 不可为空,则在 C# 中检查 struct 是否为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7894719/

相关文章:

asp.net-mvc - 如何使用 jquery 或 ajax 更新 MVC 项目的 C#/asp.net 中的 razor 部分 View

c# - 如何根据元组列表中另一个项目的值获取另一个项目的值?

c# - 根据顶点和点获取抛物线/圆弧

c# - 十六进制值 0x00 是加载 XML 文档的无效字符

c# - ASP.NET 存储交叉请求数据

c# - 在innerXML 中获取引号以作为“

c# - 将不同版本的 c# 和 .NET Framework 与 dll 一起使用

c# - C#3 和 4 中扩展方法的区别

c#-4.0 - ADO.Net (Azure AD) 错误 "keyword not supported : authentication "

.net - 为什么 Windows.Forms 在 System 而不是 Microsoft?