简体   繁体   English

检查值和引用类型是否为“ null”

[英]Check for 'null' on value and reference types

I'm currently a little confused about checking for 'null' (empty, not available, without value) on value and or reference types. 目前,我对检查值和/或引用类型的“空”(空,不可用,无值)感到有些困惑。 There seem to be a lot of possible ways to do so and all of them are frequently used. 似乎有很多可能的方法可以做到这一点,并且它们都是经常使用的。

Let's say I've got the following extension method which can be used somehow similar to a maybe monad: 假设我有以下扩展方法,该方法可以某种方式类似于monad来使用:

public static TResult UseWith<T, TResult>(this T value, Func<T, TResult> action)
{
    // if value not null
    //     execute action
    // else return the default value of 'TResult'
}

So? 所以? How do I check for null? 如何检查空值?

if(value != null)

or (which checks for null on reference types, but for default on value types) 或(检查引用类型为null,但值类型为默认值)

if(!Equals(value, default(T))

or 要么

if(!EqualityComparer<T>.Default.Equals(value, default(T))

or (with precheck) 或(带预检查)

 if (!typeof(T).IsValueType)
 {
     if (Equals(source, default(T))) 
          return TResult; 
 }

Or is it better to create 2 methods with restrictions? 还是创建两个有限制的方法更好?

 public static TResult UseWith<T, TResult>(this T value, Func<T, TResult> action)
    where T : class
 {
    if(value == null)

  public static TResult UseWith<T, TResult>(this T value, Func<T, TResult> action)
    where T : struct
 {
    if(value.HasValue)

The pseudocode in your first snippet will simply work exactly as you want it to. 第一个代码段中的伪代码将完全按照您希望的方式工作。 A variable that is typed as an unbounded generic argument can be compared to null using the == operator. 可以使用==运算符将类型为无界泛型参数的变量与null进行比较。 The code will compile, and it will simply evaluate to false whenever T is a non-nullable value type. 该代码将进行编译,并且只要T为不可为空的值类型,它将简单地评估为false

You don't want to compare T to the default value, because the default value may not be null . 您不想将T与默认值进行比较,因为默认值不能为null

There is no need to explicitly check if T is a value type, or have separate overloads for reference/value types, as the == operator handles this when it's JITted. 无需显式检查T是否为值类型,或者对于引用/值类型有单独的重载,因为==运算符在JITted时会对此进行处理。

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

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