最有效的方法来检查,如果对象是值类型方法来、最有效、类型

2023-09-02 02:10:14 作者:是吃奥利奥的奥利给

警告:本code很烂,查阅安东尼的评论

这是更快?

1。

  public bool IsValueType<T>(T obj){
       return obj is ValueType;
  }

2。

  public bool IsValueType<T>(T obj){
       return obj == null ? false : obj.GetType().IsValueType;
  } 

3。

  public bool IsValueType<T>(T obj){
       return default(T) != null;
  }

4.Something其他

4.Something else

推荐答案

你是不是真正的测试对象 - 要测试的键入的。要调用这些,调用者必须知道的类型,但是......咩。给定一个签名&LT; T&GT;(T obj)以的唯一明智的答案是:

You aren't really testing an object - you want to test the type. To call those, the caller must know the type, but... meh. Given a signature <T>(T obj) the only sane answer is:

public bool IsValueType<T>() {
    return typeof(T).IsValueType;
}

如果我们想用一个实例对象类型推断用途:

or if we want to use an example object for type inference purposes:

public bool IsValueType<T>(T obj) {
    return typeof(T).IsValueType;
}

这并不需要拳(的GetType()是拳击),并且不会有问题,可空&LT; T&GT; 。当你路过对象 ...

this doesn't need boxing (GetType() is boxing), and doesn't have problems with Nullable<T>. A more interesting case is when you are passing object...

 public bool IsValueType(object obj);

在这里,我们已经拥有了大量的问题,,因为这可能是一个空的可空&LT; T&GT; (一个struct)或类。但合理的尝试是:

here, we already have massive problems with null, since that could be an empty Nullable<T> (a struct) or a class. But A reasonable attempt would be:

public bool IsValueType(object obj) {
    return obj != null && obj.GetType().IsValueType;
}

但请注意,这是不正确(和不可修复)空可空&LT; T&GT; 秒。在这里,就变得毫无意义担心拳击,因为我们已经装箱。

but note that it is incorrect (and unfixable) for empty Nullable<T>s. Here it becomes pointless to worry about boxing as we are already boxed.