C#readonly
时间: 2023-10-19 12:55:22 浏览: 28
C#中的`readonly`关键字用于声明只读字段。只读字段是指其值在初始化后不能被修改的字段。一旦给只读字段赋值,就不能再修改它的值。
下面是一个示例:
```csharp
public class MyClass
{
public readonly int MyReadOnlyField;
public MyClass(int value)
{
MyReadOnlyField = value;
}
}
```
在上面的示例中,`MyReadOnlyField`是一个只读字段。它在构造函数中被赋值后,就不能再被修改了。
请注意,只读字段只能在声明时或构造函数中进行赋值,而不能在其他方法或属性中修改其值。这使得只读字段在需要保持不变性的情况下非常有用。
相关问题
c# readonly
在C#中,readonly关键字用于声明只读字段。只读字段的值只能在声明时或构造函数中进行赋值,一旦赋值后就不能再修改。\[1\]与const关键字不同的是,readonly字段的值是在运行时获取的,而不是在编译期间获取的。\[1\]只读字段可以在定义的同时赋值,也可以在构造函数中进行赋值。\[2\]只读字段的属性只能有get访问器,不能有set访问器。\[3\]这样设计的目的是为了确保只读字段的值在对象创建后不会被修改。
#### 引用[.reference_title]
- *1* *2* [C#readonly关键字](https://blog.csdn.net/qq_34423913/article/details/113740707)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
- *3* [c#编程--只读关键字(readonly)](https://blog.csdn.net/weixin_45595405/article/details/121762941)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}} ] [.reference_item]
[ .reference_list ]
C# readonly
In C#, the `readonly` keyword is used to declare a field that can only be assigned a value once, either at the time of declaration or in the class's constructor. Once assigned, the value of the `readonly` field cannot be changed.
For example, the following code declares a `readonly` field `myReadOnlyField` in a class `MyClass`:
```
class MyClass
{
readonly int myReadOnlyField;
public MyClass(int value)
{
myReadOnlyField = value;
}
}
```
In this example, `myReadOnlyField` can only be assigned a value once, either at the time of declaration or in the `MyClass` constructor. After that, the value cannot be changed.