Redundancy in C#?

前端 未结 17 1540
猫巷女王i
猫巷女王i 2021-02-13 19:28

Take the following snippet:

List distances = new List();

Was the redundancy intended by the language designers? If so, wh

17条回答
  •  一整个雨季
    2021-02-13 19:46

    The reason the code appears to be redundant is because, to a novice programmer, it appears to be defining the same thing twice. But this is not what the code is doing. It is defining two separate things that just happen to be of the same type. It is defining the following:

    1. A variable named distances of type List.
    2. An object on the heap of type List.

    Consider the following:

    Person[] coworkers = new Employee[20];
    

    Here the non-redundancy is clearer, because the variable and the allocated object are of two different types (a situation that is legal if the object’s type derives from or implements the variable’s type).

提交回复
热议问题