首页 > 解决方案 > 结构中的只读字段

问题描述

也许你们中的一些人对此问题没有任何意义,但如果你们中的任何人能回答我,我感到很困惑。

假设我有这个结构并且它有一个或多个只读字段,我如何通过构造函数为其赋值。

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();

该字段是只读的,那么代码如何以这种方式工作?

标签: c#structfieldreadonly

解决方案


因为 readonly 字段可以在声明时分配,也可以在它的类构造函数中分配


推荐阅读