Default value for generics

前端 未结 3 2070
温柔的废话
温柔的废话 2020-12-03 21:20

How do I create the default for a generic in VB? in C# I can call:

T variable = default(T);
  1. How do I do this in VB?
  2. If this
3条回答
  •  心在旅途
    2020-12-03 21:31

    Question 1:

    Dim variable As T
    ' or '
    Dim variable As T = Nothing
    ' or '
    Dim variable As New T()
    

    Notice that the latter only works if you specify the Structure constraint for the generic type (for reference types, New T() in VB does something else than default(T) in C#).

    Question 2:

    For value types all members of the struct are “nulled” out, i.e. all reference type members are set to null (Nothing) and all value types are in turn nulled out.

    And no, since string is a reference type, it does not result in "" for strings as suggested in the other answer.

    Question 3:

    No, there's no way to specify this. There are some threads about this on Stack Overflow already, e.g. here. Jon has posted an excellent explanation why this is.

提交回复
热议问题