Is there a way to define a getter function in C# as ReadOnly like VB.NET?
In C#, it is possible to define a readonly getter function by not defining the set function like so:
private int _id;
public int Id
{
get { return _id; }
// no setter defined
}
in VB.NET
Private _id as Integer
Public Readonly Property Id() As Integer
Get
Return _id
E开发者_JAVA技巧nd Get
End Property
Is it possible to tag such a function as readonly like you can in VB .NET in order to be more verbose?
I don't know what the ReadOnly gives you in VB. I guess the most explicit you can get is actually less verbose:
public int Id { get; private set; }
In C#, readonly indicates that a field's value is set during creation of the object and is unchangeable after the constructor exits. You could achieve that via:
private readonly int _id; // note field marked as 'readonly'
public int Id
{
get { return _id; }
}
Unfortunately automatic properties (like I show in the first code snippet) are not allowed to be readonly. That is, you must enforce read-only semantics yourself by ensuring that none of your class's code calls the private setter after the constructor exits. I guess this is different to what you're referring to by VB's usage of ReadOnly though.
EDIT As Thomas points out, having no getter is different from having a private one. However VB's usage of ReadOnly is different to the C# one, at least when used with properties:
' Only code inside class employee can change the value of hireDateValue.
Private hireDateValue As Date
' Any code that can access class employee can read property dateHired.
Public ReadOnly Property dateHired() As Date
Get
Return hireDateValue
End Get
End Property
To a C# programmer, the ReadOnly keyword would seem redundant. It is already implied by the fact that no setter exists.
As far as fields are concerned, C# and VB seem equivalent.
加载中,请稍侯......
精彩评论