简体   繁体   English

C# 概念拆箱

[英]C# Concept Unboxing

I'm trying to learn C# Boxing and Unboxing Concept.我正在尝试学习 C# 装箱和拆箱概念。 I filled the list of objects with integers and then I wanted to summarize them as result in console output.我用整数填充了对象列表,然后我想在控制台输出中总结它们。

List<object> listOfObjects = new List<object>();
//var listOfObjects = new List<object>();

//adding first string to list
listOfObjects.Add("First string");

//adding integers to list
for (int j = 0; j < 5; j++)
{
    listOfObjects.Add(j);
}
listOfObjects.Add("Second string");
for (int k = 5; k < 10; k++)
{
    listOfObjects.Add(k);
}
foreach (var obj in listOfObjects)
{
    Console.WriteLine(obj);
}
var sum = 0;
for (var l = 0;  l < 4;  l++)
{
    sum += (int)listOfObjects[l];            
}
Console.WriteLine(sum);

but output throws exception但输出抛出异常

Exception thrown: 'System.InvalidCastException' in ConsoleApp.exe An unhandled exception of type 'System.InvalidCastException' occurred抛出异常:ConsoleApp.exe 中的“System.InvalidCastException”发生类型为“System.InvalidCastException”的未处理异常

sum += (int)listOfObjects[l] // this unboxing cause compile error

Someone knows why?有人知道为什么吗? I used the example from MSDN resource .我使用了MSDN 资源中的示例。

The problem is lines like these:问题是这样的行:

listOfObjects.Add("First string");

This adds a string to the list and it makes no sense to try to convert that to an int .这将一个string添加到列表中,尝试将其转换为int是没有意义的。

Remove lines such as this and you should get an output.删除诸如此类的行,您应该会得到一个输出。

Since your listOfObjects is a List whose contents are of type object , you can add anything to it.由于您的listOfObjects是一个内容类型为objectList ,您可以向其中添加任何内容。 You first add a string , which is an object.您首先添加一个string ,它是一个对象。 Then you add a bunch of numbers of type int , which is a value type , so the numbers are boxed into an object before they are added to the list.然后你添加一堆int类型的数字,这是一个值类型,所以这些数字在被添加到列表之前被装箱到一个object中。 Then you add another string .然后添加另一个string Then you add another bunch of numbers of type int , again boxing as before.然后添加另一组int类型的数字,再次像以前一样装箱。

Your problem is in the last loop, where you loop over the first 4 elements.您的问题出在最后一个循环中,在那里您循环了前 4 个元素。 The first element is a string , so you cannot cast it to an int.第一个元素是string ,因此您不能将其强制转换为 int。

'System.InvalidCastException' -> says you that you have made wrong cast. 'System.InvalidCastException' -> 表示您进行了错误的转换。

So if we will take special range of items from list, after cast them to ( int ), then we get result of unboxing .因此,如果我们从列表中获取特殊范围的项目,在它们转换为 ( int ) 之后,我们将得到unboxing 的结果。

Because boxing has been made when you added numbers to Lis.因为当你把数字加到 Lis 时,拳击就已经完成了。

Hope this detailed response will be more friendfull.希望这个详细的回复会更友好。

List listOfObjects = new List(); List listOfObjects = new List(); //var listOfObjects = new List(); //var listOfObjects = new List();

        //adding first string to list
        listOfObjects.Add("First string");

        //adding integers to list
        for (int j = 0; j < 5; j++)
        {
            listOfObjects.Add(j);
        }
        listOfObjects.Add("Second string");
        for (int k = 5; k < 10; k++)
        {
            listOfObjects.Add(k);
        }
        foreach (var obj in listOfObjects)
        {
            Console.WriteLine(obj);
        }
        var sum = 0;
        for (var l = 0; l < 4; l++)
        {

            var a = listOfObjects[l].GetType();

            if (a == typeof(int))
            {
                sum += (int)listOfObjects[l];
                Console.WriteLine("I've get an integer type.");

            }
            Console.WriteLine("I've get only string type.");
        }
        Console.WriteLine(sum);

        Console.Read();

Hope this modified sample will help you.希望这个修改后的样本对你有帮助。 Good Luck!祝你好运!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM