问题描述
使用以下代码段:
List<int> distances = new List<int>();
语言设计者是否打算提供冗余?如果是这样,为什么?
Was the redundancy intended by the language designers? If so, why?
推荐答案
代码看起来多余的原因是,对于一个新手程序员来说,它似乎两次定义了相同的东西.但这不是代码在做什么.它定义了两个恰好属于同一类型的独立事物.它定义了以下内容:
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:
- 一个名为distances的变量,类型为
List<int>
. -
List<int>
类型的堆上的对象.
- A variable named distances of type
List<int>
. - An object on the heap of type
List<int>
.
请考虑以下内容:
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).
这篇关于C#中的冗余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!