这些代码在c#的内存中是否安全?

Hz *_*ang 3 c# unity-game-engine

我对以下代码有疑问.

首先,这些代码运作良好.

但是,没有关于Student类中"课程"的定义的声明.如果在Student的构造函数中,参数是常量,这些代码是否安全?谢谢你的帮助!:)

public class Student
{
    public string name;
    public int age;
    public string[] courses;
    public Student(string _name, int _age,params string[] _courses)
    {
        name = _name;
        age = _age;

        courses = _courses;//is this OK if _courses is constant?


    }
}
public class work : MonoBehaviour 
{
    void Start()
    {
       /*
        string[] courses={"math", "English"};
        Student Tom = new Student("Tom",18,courses);
        //It's wrong!
       */
        Student Tom = new Student("Tom", 18, "math", "English");
        string Tom_text = JsonUtility.ToJson(Tom);
        Debug.Log(Tom_text);
    }
}
Run Code Online (Sandbox Code Playgroud)

Cod*_*shi 5

你拥有它的方式,任何人都可以Student随时更改对象.

如果您不希望任何人Student在创建对象后对其进行任何更改,请将其设置为不可变为:

public class Student
{
    public string Name { get; private set; }
    public int Age { get; private set; }
    public IEnumerable<string> Courses { get; private set; }
    public Student(string name, int age, params string[] courses)
    {
        this.Name = name;
        this.Age = age;

        this.Courses = courses;
    }
}
Run Code Online (Sandbox Code Playgroud)

现在人们无法更改属性,因为setter是私有的.

要遵循.NET命名约定,请不要-在参数名称中使用下划线,并使用Pascal Notation作为属性名称.我删除了下划线并使用Pascal Notation作为属性名称.

编辑

@diemaus在C#6的评论中提到了一个很好的观点:

您实际上可以完全删除私有集,然后保留它{ get; }.只要您只在构造函数中设置属性,就允许这样做.

  • 你实际上可以完全删除`private set`,然后留下它`{get; }`.只要您只在构造函数中设置属性,就允许这样做. (3认同)