【问题标题】:When do I use Boxing and Unboxing? [duplicate]我什么时候使用装箱和拆箱? [复制]
【发布时间】:2014-12-14 16:18:09
【问题描述】:

我知道装箱将值类型转换为对象和取消装箱将对象转换为值类型。 示例:

int num = 1;
Object obj = num;      //boxing
int num2 = (int)obj    //unboxing

但是当我在现实生活中使用它时(当我编写一些代码时)? 我从不将 Int 赋值给 Object (或者我是这么认为的,我没有明确写)

【问题讨论】:

  • 这是一个例子:stackoverflow.com/questions/14561382/… 另一个例子是使用旧集合(在 ArrayList 等泛型之前)
  • 例如,当您将不同类型的变量传递给方法时,通常会使用装箱。 String.Format 接受的参数是对象,因此您可以混合放入字符串中的数据类型:string s = String.Format("The {1} is {0}", 42, "answer"); String.Concat 可以将对象的集合转换为字符串并连接:string s = String.Contcat("one", 2, "three", 4);您使用 + 运算符连接,编译器将生成对 String.Concat 的调用来完成工作:string s = "one" + 2 + "three" + 4;

标签: c# object boxing


【解决方案1】:

装箱/拆箱对于您可能拥有不同事物的集合的情况很有用,例如,其中一些是原语,而另一些是对象类型,例如List<object>。事实上,这就是他们在 Boxing and Unboxing 文档页面中给出的示例,如果您搜索“msdn boxing:”

// List example. 
// Create a list of objects to hold a heterogeneous collection  
// of elements.
List<object> mixedList = new List<object>();

// Add a string element to the list. 
mixedList.Add("First Group:");

// Add some integers to the list.  
for (int j = 1; j < 5; j++)
{
    // Rest the mouse pointer over j to verify that you are adding 
    // an int to a list of objects. Each element j is boxed when  
    // you add j to mixedList.
    mixedList.Add(j);
}

// Add another string and more integers.
mixedList.Add("Second Group:");
for (int j = 5; j < 10; j++)
{
    mixedList.Add(j);
}

// Display the elements in the list. Declare the loop variable by  
// using var, so that the compiler assigns its type. 
foreach (var item in mixedList)
{
    // Rest the mouse pointer over item to verify that the elements 
    // of mixedList are objects.
    Console.WriteLine(item);
}

// The following loop sums the squares of the first group of boxed 
// integers in mixedList. The list elements are objects, and cannot 
// be multiplied or added to the sum until they are unboxed. The 
// unboxing must be done explicitly. 
var sum = 0;
for (var j = 1; j < 5; j++)
{
    // The following statement causes a compiler error: Operator  
    // '*' cannot be applied to operands of type 'object' and 
    // 'object'.  
    //sum += mixedList[j] * mixedList[j]); 

    // After the list elements are unboxed, the computation does  
    // not cause a compiler error.
    sum += (int)mixedList[j] * (int)mixedList[j];
}

// The sum displayed is 30, the sum of 1 + 4 + 9 + 16.
Console.WriteLine("Sum: " + sum);

// Output: 
// Answer42True 
// First Group: 
// 1 
// 2 
// 3 
// 4 
// Second Group: 
// 5 
// 6 
// 7 
// 8 
// 9 
// Sum: 30

【讨论】:

    猜你喜欢
    • 2011-02-28
    • 2015-02-23
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2011-07-03
    相关资源
    最近更新 更多