加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

vb.net – 构造函数中的构造函数

发布时间:2020-12-17 07:15:57 所属栏目:百科 来源:网络整理
导读:这是一个坏主意吗?在公共构造函数中调用泛型私有构造函数是否会创建多个实例,或者这是初始化类变量的有效方法? Private Class MyClass Dim _msg As String Sub New(ByVal name As String) Me.New() 'Do stuff End Sub Sub New(ByVal name As String,ByVal
这是一个坏主意吗?在公共构造函数中调用泛型私有构造函数是否会创建多个实例,或者这是初始化类变量的有效方法?

Private Class MyClass
    Dim _msg As String

    Sub New(ByVal name As String)
        Me.New()
        'Do stuff
    End Sub

    Sub New(ByVal name As String,ByVal age As Integer)
        Me.New()
        'Do stuff
    End Sub

    Private Sub New() 'Initializer constructor
        Me._msg = "Hello StackOverflow"
        'Initialize other variables
    End Sub
End Class

解决方法

这是一种有效的方法.有一些警告可以调用新函数:

The Sub New constructor can run only once when a class is created. It
cannot be called explicitly anywhere other than in the first line of
code of another constructor from either the same class or from a
derived class.

在MSDN上阅读有关object lifetime的更多信息.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读