简体   繁体   English

如果结构不可为空,则在 C# 中检查结构是否为空

[英]Check for null for struct in C# if struct isn't nullable

I have some generic method我有一些通用方法

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

It works good if T is class.如果T是类,则效果很好。 But what should I do if T is struct?但是如果T是 struct 该怎么办呢? How can I check if result == default(T) in case if T is struct ?如果Tstruct我如何检查result == default(T)

PS I don't want to use the constraint where T: class or Nullable types. PS 我不想使用约束where T: classNullable类型。

A more idiomatic way of doing this would be to follow the lead of things like int.TryParse .这样做的一种更惯用的方法是遵循int.TryParse之类的int.TryParse

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

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

    if(func(out value))
    {

    }
}

If T is compiled to be a struct then the comparison with null will always evaluate to false .如果T被编译为struct则与null的比较将始终评估为false This is covered in section 7.9.6 of the C# language spec这在 C# 语言规范的第 7.9.6 节中有介绍

If an operand of a type parameter type T is compared to null, and the runtime type of T is a value type, the result of the comparison is false.如果将类型参数类型 T 的操作数与 null 进行比较,并且 T 的运行时类型是值类型,则比较结果为 false。

Consider using default(T):考虑使用 default(T):

private T SomeMethod<T>(Func<T> func)
{
  var result = func();
  if (result.Equals(default(T)))
  {
    // handling ...
    return default(T);
  }
  return result;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM