2014-12-14 3 views
-2

Я знаю, что бокс конвертирует тип значения в объект и unboxing преобразует объект в тип значения. Пример:Когда я использую Бокс и Unboxing?

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

Но когда я использую его в реальной жизни (когда я пишу код)? Я никогда не назначаю Int в Object (или это то, что я так думаю, я не писал его явно)

+0

Вот один пример: http://stackoverflow.com/questions/14561382/why-net- has-no-generic-version-of-thread-start Другим примером является использование старых коллекций (до таких дженериков, как ArrayList). –

+0

Бокс, например, обычно используется, когда вы передаете переменные разных типов в метод. 'String.Format' принимает параметры - это объекты, поэтому вы можете смешивать типы данных, которые помещаются в строку: ' string s = String.Format («{1} is {0}", 42, «answer»); ' ' String.Concat' может принимать коллекцию объектов, которые превращаются в строки и объединяются: 'string s = String.Contcat (« один », 2,« три », 4); ' То же самое происходит при объединении с помощью оператора' + ', компилятор будет генерировать вызов' String.Concat' для выполнения работы: 'string s =" one "+ 2 +" three "+ 4 ; ' – Guffa

ответ

0

Бокс/распаковка полезен для ситуаций, когда у вас может быть, например, коллекция несопоставимых вещей, некоторые из них которые являются примитивами, а другие являются объектами, такими как List<object>. В самом деле, это пример они дают на странице Boxing and Unboxing документации, которая приходит, если вы ищете «бокс: MSDN»

// 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 
Смежные вопросы