如何测试一个值是否是盒装在C#/。NET?

编程入门 行业动态 更新时间:2024-10-22 16:35:40
本文介绍了如何测试一个值是否是盒装在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?

本文发布于:2023-11-06 06:51:18,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1562983.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:测试   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!