<分区>
装箱和拆箱似乎很重要。对象类型的用途如此之多,以至于我们真的必须非常注意这一点吗?
当需要装箱/拆箱时,有哪些非常实用的实例?
<分区>
装箱和拆箱似乎很重要。对象类型的用途如此之多,以至于我们真的必须非常注意这一点吗?
当需要装箱/拆箱时,有哪些非常实用的实例?
最佳答案
视情况而定。
我认为现在这个问题不像以前那么严重了。如果您确保在框架内使用通用集合(即:使用 List<T>
而不是 ArrayList
),那么这对您来说可能不是主要问题。
这是 .NET 1.1 中的一个巨大问题,因为大多数集合都在 object
上工作,因为没有通用集合。在 .NET 1.1 中,每次添加 int
,例如,在大多数收藏中,它被装箱,而每次您将其拉出时,它都会被拆箱。如果您在一个紧密的循环中执行此操作,则很容易出现问题。它还导致了许多错误,例如尝试拆箱并转换为不合适的类型,从而引发异常。
区别如下:
在 .NET 1.1 中,您通常会使用类似 ArrayList
的东西:
ArrayList list = new ArrayList();
list.Add(1); // These are all boxing - the integer is getting boxed to add
list.Add(2);
list.Add(3);
foreach(object item in list)
{
// Unboxing required here:
int value = (int)item;
Console.WriteLine(value);
}
更糟糕的是,由于这不是类型安全的,您很容易因为 unbox and conversion can't happen in a single operation 而导致严重的问题。 :
foreach(object item in list)
{
// Trying to unboxing into the wrong type here...
// This will raise an exception at runtime, but compile fine!
double value = (double)item;
Console.WriteLine(value);
}
但是,在 .NET 2 及更高版本中,您可以使用泛型集合:
List<int> list = new List<int>();
list.Add(1); // No boxing now, since it's using generics!
list.Add(2);
list.Add(3);
foreach(int value in list) // This is now typesafe, and doesn't cause an unboxing operation
{
Console.WriteLine(value);
}
今天有时仍然需要装箱和拆箱。例如,Reflection完全适用于 object
而不是具体类型,因此它需要装箱值才能使用 FieldInfo.SetValue 之类的方法.
关于c# - .NET 中的装箱/拆箱,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4000777/