如何防止构造函数初始化的属性值被覆盖

How to prevent the values of properties initialized by the constructor from being overwritten

我是编程新手,正在尝试防止 Program class 覆盖由 Person [=17= 的构造函数初始化的属性值]

这是我的代码:请查看突出显示我正在努力实现的目标的评论

using System;

namespace Test
{
    class Program
    {
        class Person
        {
            public string FName { get; set; }
            public string LName { get; set; }

            public Person(string fName, string lName)
            {
                FName = fName;
                LName = lName;
            }

            public override string ToString()
            {
                return FName + " " + LName;
            }

        }

        static void Main()
        {
            Person person = new Person("Adam", "Lake");
            person.FName = "Fabio";      // I want to prevent this 
            person.LName = "Scagliola";  // I want to prevent this 
            Console.WriteLine(person);
        }

    }
}

将您的属性 FirstNameLastName 更改为 Read-only Auto-Implemented Properties

public string FirstName { get; }
public string LastName { get; }

表示只能从Person构造函数中设置值