简体   繁体   English

ReadOnly in C#vs in VB.NET

[英]ReadOnly in C# vs in VB.NET

It seems that VB.NET and C# readonly keyword have some differences... 似乎VB.NET和C# readonly关键字有一些差异......

Say, a ReadOnly property in C# can be assigned in some conditions, but in VB.NET - never? 比方说,C#中的ReadOnly属性可以在某些条件下分配,但在VB.NET中 - 永远不会?

In C#, readonly is a field modifier. 在C#中, readonly是一个字段修饰符。 It specifies that the field can be assigned to only on initialization or in the constructor. 它指定只能在初始化或构造函数中分配字段。

VB.NET is the same, except that ReadOnly is also a property modifier. VB.NET是相同的,除了ReadOnly也是属性修饰符。 It specifies that the property cannot be assigned to - ie, it is a getter. 它指定不能将属性分配给 - 即它是一个吸气剂。

In VB.NET the read-only property is usually created to be read-only from external class. 在VB.NET中,只读属性通常被创建为从外部类只读。 If you want to set this property, you can easily do it from inside the class, by changing the realated local variable. 如果要设置此属性,可以通过更改相关的局部变量,从类内部轻松完成。

So, eg in VB 2010 所以,例如在VB 2010中

Public ReadOnly Property SomeVariable() As String

or in earlier versions, 或者在早期版本中,

Private _SomeVariable As String
Public ReadOnly Property SomeVariable() As String
    Get
        Return _SomeVariable
    End Get
End Property

you can set it from inside your class as: 你可以在课堂内设置它:

_SomeVariable = somevalue

The property value can not be modified from an external class. 无法从外部类修改属性值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM