有没有办法像VB.NET一样将C#中的getter函数定义为只读?

有没有办法像VB.NET一样将C#中的getter函数定义为只读?,c#,C#,在C#中,可以通过如下方式不定义set函数来定义readonlygetter函数: private int _id; public int Id { get { return _id; } // no setter defined } 在VB.NET中 Private _id as Integer Public Readonly Property Id() As Integer Get Return _id End Get End Property

在C#中,可以通过如下方式不定义set函数来定义
readonly
getter函数:

private int _id;

public int Id
{

   get { return _id; }
   // no setter defined
}
在VB.NET中

Private _id as Integer
Public Readonly Property Id() As Integer
    Get
       Return _id
    End Get
End Property

是否可以像在VB.NET中那样将这样的函数标记为
readonly
,以便更加详细?

我不知道
readonly
在VB中给了您什么。我想你能得到的最明确的信息实际上是更少的冗长:

public int Id { get; private set; }
在C#中,
readonly
表示字段的值在对象创建期间设置,并且在构造函数退出后不可更改。您可以通过以下方式实现:

private readonly int _id; // note field marked as 'readonly'

public int Id
{
   get { return _id; }
}
不幸的是,自动属性(如我在第一个代码片段中所示)不允许是
只读的
。也就是说,您必须自己强制执行只读语义,方法是确保在构造函数退出后,类的任何代码都不会调用私有setter。我想这与VB使用的
ReadOnly
不同

编辑正如托马斯指出的那样,没有getter与拥有私有getter是不同的。但是,与C#one不同,至少在与属性一起使用时:

' 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
对于C#程序员来说,
ReadOnly
关键字似乎是多余的。这已经暗示了一个事实,即不存在设置者


就字段而言,C#和VB似乎是等价的。

为了更详细些?!这就是vb的作用……当你说“更详细”时,你指的是什么?对于您的代码示例,如果您尝试分配给它,您将得到与在VB.NET中相同的编译器错误。Intellisense还应该将它标识为只能获取的项。@乔纳森:更详细的是,读者更清楚地看到它是只读属性,而不是通过推断它是只读属性。没有setter可以非常清楚地看到该属性是只读的…@Thomas:是的,我知道,但如果有办法将其标记为只读,那就太好了。评论现在已经足够了。有一个私人的setter和没有setter完全不同。。。这只是意味着只能从类内部访问setter。这样的属性是只读的,只能从外部读取