What is object casting?

前端 未结 3 1403
醉酒成梦
醉酒成梦 2021-01-17 03:36

I\'m a bit confused about what exactly object casting is and what it\'s used for. I\'ve read the MSDN documentation about Casting and type conversion, where I can see that f

3条回答
  •  独厮守ぢ
    2021-01-17 04:31

    A simple valid example goes back to older versions of C#. List didn't exist in that version and in order to store a collection of data you had to use a non-generic collection:

    static void Main(string[] args)
    {
       ArrayList list = new ArrayList();
       list.Add(1);
       list.Add(2);
       list.Add(3);
    
       int total = 0;
       foreach(object item in list)
          total += (int)item; // without casting, compiler never knows item is int
    
       Console.WriteLine("Total = {0}", total);
    }
    

    Another valid example is events, most events use the signature (object sender, EventArgs e). In order to access the elements of the sender, a button for example, then you need to cast:

    Button btn = (Button)sender;
    Console.WriteLine(btn.Text);
    

    It is a better practice to use the as operator over the normal casting to prevent null reference exception, but the above is just to provide valid examples.

提交回复
热议问题