c# - 结构中的只读字段
问题描述
也许你们中的一些人对此问题没有任何意义,但如果你们中的任何人能回答我,我感到很困惑。
假设我有这个结构并且它有一个或多个只读字段,我如何通过构造函数为其赋值。
struct PointWithReadOnly
{
// Fields of the structure.
public int X;
public readonly int Y;
public readonly string Name;
// Display the current position and name.
public readonly void Display()
{
Console.WriteLine($"X = {X}, Y = {Y}, Name = {Name}");
}
// A custom constructor.
public PointWithReadOnly(int xPos, int yPos, string name)
{
X = xPos;
Y = yPos;
Name = name;
}
}
要使用此结构,请添加以下内容:
PointWithReadOnly p1 = new PointWithReadOnly(50,60,"Point w/RO");
p1.Display();
该字段是只读的,那么代码如何以这种方式工作?
解决方案
因为 readonly 字段可以在声明时分配,也可以在它的类构造函数中分配
推荐阅读
- java - 类 java.math.BigInteger 不能转换为类 java.lang.Integer(java.math.BigInteger 和 java.lang.Integer 在模块 java.base 中的负载
- python - numpy中分段线性函数的总变化实现
- regex - /dev/urandom 为 Windows 10 复杂性要求生成密码
- minio - 简单的 Minio 存储桶策略
- visual-studio-code - 你如何安装Eigen?
- python - ValueError:无法将字符串转换为浮点数:'2021-08-22 19:30:00+01:00'
- javascript - React Javascript,仪表板站点的通用标题删除
- java - 检查一个数组是否包含一个可以整除所有其他整数的整数
- python-3.x - pip / pip3 不将软件包安装到最新的 python 版本
- javascript - Gatsby 网站上内置模块的 Webpack 重大更改