VB.Net Properties - Public Get, Private Set

后端 未结 6 1814
借酒劲吻你
借酒劲吻你 2021-01-31 13:32

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 prope

相关标签:
6条回答
  • 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

    0 讨论(0)
  • 2021-01-31 13:54
        Public Property Name() As String
            Get
                Return _name
            End Get
            Private Set(ByVal value As String)
                _name = value
            End Set
       End Property
    
    0 讨论(0)
  • 2021-01-31 13:55

    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

    0 讨论(0)
  • 2021-01-31 13:57

    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
    
    0 讨论(0)
  • 2021-01-31 14:04

    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
    
    0 讨论(0)
  • 2021-01-31 14:04

    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

    0 讨论(0)
提交回复
热议问题