VB.net类构造函数的简写

时间:2013-03-10 19:35:16

标签: vb.net

我倾向于制作一堆用于保存各种数据的POD类,它们通常看起来像这样:

Public class vertex
    public x as single
    public y as single
    Public sub New(x as single, y as single)
        Me.x = x
        Me.y = y
    End Sub
End class

有没有办法不写出me.class_variable_name = function_variable_with_same_name?还是一些较短的方法呢?

可能看起来像一个毫无意义的问题,但我倾向于一直制作这类课程,而且只是感觉如此冗长,一遍又一遍地写着相同的变量名。

2 个答案:

答案 0 :(得分:2)

您可以使用object initializers完全跳过构造函数:

Public Class vertex
    Public Property x As Single
    Public Property y As Single
End Class


Dim v As New vertext() With {.x = 2, .y = 4}

答案 1 :(得分:0)

构造函数有什么问题?另外,如果您不需要或想要公开它们,您可以缩小变量的范围。

Dim v As New vertext(2, 4)

Public class vertex
 Private x as single
 Private y as single
 Public sub New(x as single, y as single)
    Me.x = x
    Me.y = y
 End Sub
End class