VB.Net Properties - Public Get, Private Set

2019-03-09 06:23发布

I figured I would ask... but is there a way to have the Get part of a property available as public, but keep the set as private?

Otherwise I am thinking I need two properties or a property and a method, just figured this would be cleaner.

6条回答
放荡不羁爱自由
2楼-- · 2019-03-09 06:26
    Public Property Name() As String
        Get
            Return _name
        End Get
        Private Set(ByVal value As String)
            _name = value
        End Set
   End Property
查看更多
女痞
3楼-- · 2019-03-09 06:30

I'm not sure what the minimum required version of Visual Studio is, but in VS2015 you can use

Public ReadOnly Property Name As String

It is read-only for public access but can be privately modified using _Name

查看更多
Fickle 薄情
4楼-- · 2019-03-09 06:36

I find marking the property as readonly cleaner than the above answers. I believe vb14 is required.

Private _Name As String

Public ReadOnly Property Name() As String
    Get
        Return _Name
    End Get
End Property

This can be condensed to

Public ReadOnly Property Name As String

https://msdn.microsoft.com/en-us/library/dd293589.aspx?f=255&MSPPError=-2147217396

查看更多
爷的心禁止访问
5楼-- · 2019-03-09 06:38

Yes, quite straight forward:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set(ByVal value As String)
        _name = value
    End Set
End Property
查看更多
祖国的老花朵
6楼-- · 2019-03-09 06:39

One additional tweak worth mentioning: I'm not sure if this is a .NET 4.0 or Visual Studio 2010 feature, but if you're using both you don't need to declare the value parameter for the setter/mutator block of code:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set
        _name = value
    End Set
End Property
查看更多
萌系小妹纸
7楼-- · 2019-03-09 06:40

If you are using VS2010 or later it is even easier than that

Public Property Name as String

You get the private properties and Get/Set completely for free!

see this blog post: Scott Gu's Blog

查看更多
登录 后发表回答