How to test whether a value is boxed in C# / .NET?

后端 未结 9 1314
终归单人心
终归单人心 2020-12-13 00:32

I\'m looking for a way to write code that tests whether a value is boxed.

My preliminary investigations indicate that .NET goes out of its way to conceal the fact,

9条回答
  •  鱼传尺愫
    2020-12-13 01:22

    Similar to Allon's answer, but should return the correct answer for any type without generating a compile-time error:

    int i = 123;
    Console.WriteLine(IsBoxed(i));    // false
    
    object o = 123;
    Console.WriteLine(IsBoxed(o));    // true
    
    IComparable c = 123;
    Console.WriteLine(IsBoxed(c));    // true
    
    ValueType v = 123;
    Console.WriteLine(IsBoxed(v));    // true
    
    int? n1 = 123;
    Console.WriteLine(IsBoxed(n1));    // false
    int? n2 = null;
    Console.WriteLine(IsBoxed(n2));    // false
    
    string s1 = "foo";
    Console.WriteLine(IsBoxed(s1));    // false
    string s2 = null;
    Console.WriteLine(IsBoxed(s2));    // false
    
    // ...
    
    public static bool IsBoxed(T item)
    {
        return (item != null) && (default(T) == null) && item.GetType().IsValueType;
    }
    
    public static bool IsBoxed(T? item) where T : struct
    {
        return false;
    }
    

    (Although you could make the argument that the possible compile-time error caused by Allon's code is a feature, not a bug: if you hit a compile-time error then you're definitely not dealing with an unboxed value type!)

提交回复
热议问题