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

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

问题描述

我正在寻找一种方法来编写代码来测试一个值是否是盒装的。

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

我的初步调查显示,.NET不再隐瞒事实,这意味着 GetType() IsValueType 不要显示盒装值和未装箱值之间的差异。例如,在以下LinqPad C#表达式中,我相信 o1 是盒装的,而 i1 不是盒装的,而是我想要一种在代码中测试的方法,或者最好的方法是在查看任何变量或值时知道 ,即使它的类型是动态或对象无论是盒装还是非盒装。

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.

任何建议?

// 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");


推荐答案

尝试以下

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

通过使用泛型,我们允许该函数考虑到由编译器查看的表达式及其基础值。

By using a generic we allow the function to take into account both the type of the expression as viewed by the compiler and it's underlying value.

Console.WriteLine(IsBoxed(42));  // False
Console.WriteLine(IsBoxed((object)42)); // True
Console.WriteLine(IsBoxed((IComparable)42));  // True

编辑

有几个人要求澄清为什么这需要通用。并且质疑为什么这甚至是需要的,开发人员不能看代码,并且判断一个值是否是盒装的?试图回答这两个问题,考虑以下方法签名

A couple of people have asked for clarification on why this needs to be generic. And questioned why this is even needed at all, can't the developer just look at code and tell if a value is boxed? In an attempt to answer both those questions consider the following method signature

void Example<T>(T param1, object param2, ISomething param3) where T : ISomething {
  object local1 = param1;
  ISomething local2 = param1;
  ...
}

在这种情况下,提供的任何参数或当地人可能潜在地代表装箱价值,而且也可能很容易。不可能通过随意的检查来说明,仅检查运行时类型和参考值的组合,可以确定该值。

In this scenario any of the provided parameters or locals could potentially represent boxed values and could just as easily not be. It's impossible to tell by casual inspection, only an examination of a combination of the runtime type and the reference by which the value is held can determine that.

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

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