将Dim X作为新Y与将Dim X作为Y = New Y()
重复
我不知道这一点,但有人能解释一下两者之间的区别吗?
Sad that I don't know this, but can anyone explain the difference between:
Dim X as New Y
和
Dim X as Y = New Y()
第一个仅推断类型为Y。第二个指定类型。这使您可以编写以下内容:
The first just infers that the type is Y. The second specifies it. This allows you to write things like:
Dim X as IList(Of String) = New List(Of String)
然后限制了使用 List(Of String)$的选择范围c $ c>-这意味着以后您可能会选择使用
IList(Of String)
的不同实现,并且仍会编译。
That then limits the scope of the choice to use List(Of String)
- which means that later on you might choose to use a different implementation of IList(Of String)
, and it'll still compile.
当然,较短的版本确实具有简洁性的优点-如果类型名非常长(例如,使用嵌套泛型),则这很重要。对于匿名类型,您也不能表示X类型。
Of course, the shorter version does have the benefit of brevity - which can be important if you have very long type names (e.g. using nested generics). It's also required for anonymous types, where you can't express the type of X.