VB.Net 属性 - 公共获取,私有集

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1462673/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 14:27:08  来源:igfitidea点击:

VB.Net Properties - Public Get, Private Set

vb.netpropertiesscope

提问by RiddlerDev

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?

我想我会问......但是有没有办法让属性的 Get 部分公开可用,但保持设置为私有?

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

否则我想我需要两个属性或一个属性和一个方法,只是想这会更干净。

回答by JDunkerley

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

回答by Breeze

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

我不确定 Visual Studio 所需的最低版本是多少,但在 VS2015 中您可以使用

Public ReadOnly Property Name As String

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

它对于公共访问是只读的,但可以使用 _Name

回答by Dan

    Public Property Name() As String
        Get
            Return _name
        End Get
        Private Set(ByVal value As String)
            _name = value
        End Set
   End Property

回答by Mass Dot Net

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 valueparameter for the setter/mutator block of code:

值得一提的另一个调整:我不确定这是 .NET 4.0 还是 Visual Studio 2010 功能,但如果您同时使用两者,则不需要为 setter/mutator 代码块声明value参数:

Private _name As String

Public Property Name() As String
    Get
        Return _name
    End Get
    Private Set
        _name = value
    End Set
End Property

回答by Adam H

I find marking the propertyas readonlycleaner than the above answers. I believe vb14 is required.

我发现将其标记propertyreadonly比上述答案更干净。我相信 vb14 是必需的。

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

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

回答by ChrisG

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

如果您使用的是 VS2010 或更高版本,那就更容易了

Public Property Name as String

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

您可以完全免费获得私人财产和获取/设置!

see this blog post: Scott Gu's Blog

请参阅此博客文章:Scott Gu 的博客