如何确定非null对象是否为Nullable结构?

sma*_*man 5 c# reflection nullable value-type c#-4.0

反正知道这个吗?

我找到一篇帖子,询问一个非常类似的问题, 如何检查一个对象是否可以为空? 答案解释了如果可以访问通用类型参数,如何确定对象是否可为空.这是通过使用来完成的Nullabe.GetUnderlyingType(typeof(T)).但是,如果您只有一个对象并且它不为null,您能否确定它是否实际上是Nullable ValueType?

换句话说,有没有比单独检查每个可能的可空值类型更好的方法来确定盒装结构是否是值类型?

void Main(){
    Console.WriteLine(Code.IsNullableStruct(Code.BoxedNullable));
} 


public static class Code{
    private static readonly int? _nullableInteger = 43;

    public static bool IsNullableStruct(object obj){
                  if(obj == null) throw new ArgumentNullException("obj");
                  if(!obj.GetType().IsValueType) return false;
                  return IsNullablePrimitive(obj);
            }
    public static bool IsNullablePrimitive(object obj){
         return obj is byte? || obj is sbyte? || obj is short? || obj is ushort? || obj is int? || obj is uint? || obj is long? || obj is ulong? || obj is float? || obj is double? || obj is char? || obj is decimal? || obj is bool? || obj is DateTime? || obj is TimeSpan?;
    }

    public static object BoxedNullable{
        get{ return _nullableInteger; }
    }
}
Run Code Online (Sandbox Code Playgroud)

-

更新

在MSDN上发现了这篇文章,它说你无法通过调用来确定一个类型是否是一个Nullable结构GetType().

-

更新#2

显然我建议的方法也不起作用,因为它int x = 4; Console.WriteLine(x is int?);是真的.(见评论)

Ric*_*key 4

引用乔恩·斯基特在您链接的问题中的评论:

不存在装箱可为空类型这样的东西 - Nullable 被装箱为空引用或装箱 int

BoxedNullable因此,在您的示例程序中,当传递IsNullableStruct给以 an作为参数的时间时object,该值已经是装箱的43,不再是可为空的任何东西。具有讽刺意味的x is int?是,true对于任何int、可为空或其他情况,这只会增加混乱。

无论如何,根据乔恩的评论,你原来的问题似乎没有意义。