Dim X as New Y vs. Dim X as Y = New Y()

前端 未结 3 1636
借酒劲吻你
借酒劲吻你 2021-01-13 07:54

Duplicate

Whats the difference between declaring as new and as something new something i

Sad that I don\'t know this, but can anyo

3条回答
  •  太阳男子
    2021-01-13 08:41

    Jon Skeet has already provided the correct answer, but I thought I'd add a little extra...

    Although it was not specifically your question, there is an important difference between

    Dim X = New Y()
    

    and

    Dim X As Y = New Y()
    

    The differences here actually depend on the version of VB.NET you are using.


    VB.NET 7 & 8

    Dim X = New Y()
    

    This defines X as a variable of type object (System.Object), then creates an object of type Y and assigns it to X. Note that this only works when you've defined Option Strict Off, otherwise it won't even compile. It's really just a carry-over from the syntax of the days of VB6 and earlier, and is generally discouraged.

    Dim X as Y = New Y()
    

    This does exactly the same, except that X is now strongly-typed, in other words it is of type Y rather than object (from which all types inherit, including value types when they are boxed).

    VB.NET 9 and subsequently

    Dim X = New Y()
    

    The difference here (for the newer version of VB.NET) is that type inference is taking effect here. Because you don't specify any type, but it is obvious to the compiler that New Y() returns an instance of type Y, it automatically infers that the type of X should be Y, which is a lot more specific than object. Type interference also works on more complex expressions.

    Dim X as Y = New Y()
    

    This is interepreted in precisely the same was as in VB.NET 7 & 8.


    To conclude, you can effectively replace

    Dim X As New Y()
    

    with

    Dim X = New Y()
    

    in VB.NET 9 and the compiler will interpret the two lines exactly the same because of type inference. In earlier versions, however, the second line will be weakly typed (of type object), which is not advisable. Again, not a direct answer to the question, but I thought this might be helpful to point out.

提交回复
热议问题