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

后端 未结 9 1304
终归单人心
终归单人心 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:15

    This approach is similar to Jared Par's answer. But I think !typeof(T).IsValueTypeis cleaner than enumerating all types which could contain a boxed value.

    public static bool IsBoxed(T value)
    {
        return !typeof(T).IsValueType && (value != null) && value.GetType().IsValueType;
    }
    

    Unlike Jared's code this will handle the case where T is System.ValueType correctly.

    Another subtle point is that value.GetType().IsValueType comes after !typeof(T).IsValueType since otherwise GetType() would create a temporary boxed copy of the value.

提交回复
热议问题