如何测试一个值是否是盒装在C#/。NET? [英] How to test whether a value is boxed in C# / .NET?

查看:101
本文介绍了如何测试一个值是否是盒装在C#/。NET?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方式来写code测试一个值是否是盒装。

我的preliminary调查显示,.NET超出它的方式隐瞒事实,即的GetType() IsValueType 不露装箱值和拆箱值之间的差异。例如,在下面的LinqPad C#EX pressions,我有信心, 01 是盒装和 I1 终止没有盒装,但是我想办法在code测试它,或者退而求其次,就无从知道的肯定的时候,在任何一个变量或值看,即使它的类型是动态或对象,无论是盒装还是不装箱。

任何意见?

  //盒装? - 没有办法从这些答案告诉!
对象01 = 123;
o1.GetType()转储(o1.GetType())。
o1.GetType()IsValueType.Dump(o1.GetType()IsValueType。);

//不是盒装? - 没有办法从这些答案告诉!
INT I1 = 123;
i1.GetType()转储(i1.GetType())。
i1.GetType()IsValueType.Dump(i1.GetType()IsValueType。);
 

解决方案

下面是一些简单的辅助方法来检查,如果一个变量是一个盒装的整数:

 公共静态布尔IsBoxed(对象项)
{
    返回true;
}

公共静态布尔IsBoxed< T>(T项),其中T:结构
{
    返回false;
}
 

只需拨打 IsBoxed(...)您的变量:

  IsBoxed(01)//计算结果为真
IsBoxed(I1)//计算结果为假
 

这完成,当然不算什么,。到底为什么你需要知道,如果一个值是盒装还是不?

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, meaning that GetType() and IsValueType don't reveal the difference between a boxed value and an unboxed value. For example, in the following LinqPad C# expressions, I have faith that o1 is boxed and i1 is not boxed, but I would like a way to test it in code, or, second best, a way to know FOR SURE when looking at any variable or value, even if its type is "dynamic" or "object," whether it's boxed or not boxed.

Any advice?

// boxed? -- no way to tell from these answers!
object o1 = 123;
o1.GetType().Dump("o1.GetType()");
o1.GetType().IsValueType.Dump("o1.GetType().IsValueType");

// not boxed? -- no way to tell from these answers!
int i1 = 123;
i1.GetType().Dump("i1.GetType()");
i1.GetType().IsValueType.Dump("i1.GetType().IsValueType");

解决方案

Here are some simple helper methods to check if a variable is a boxed integer:

public static bool IsBoxed(object item)
{
    return true;
}

public static bool IsBoxed<T>(T item) where T : struct
{
    return false;
}

Just call IsBoxed(...) on your variable:

IsBoxed(o1) // evaluates to true
IsBoxed(i1) // evaluates to false

This accomplishes nothing, of course. Why exactly do you need to know if a value is boxed or not?

这篇关于如何测试一个值是否是盒装在C#/。NET?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆