gpt4 book ai didi

C# 私有(private)成员可见性

转载 作者:可可西里 更新时间:2023-11-01 08:03:05 26 4
gpt4 key购买 nike

我们的业务模型中有一个 Student 类。让我感到奇怪的是,如果我们从另一个学生操纵一个学生,学生的私有(private)成员是可见的,这是为什么?

   class Program {
static void Main(string[] args) {

Student s1 = new Student();
Student s2 = new Student();

s1.SeePrivatePropertiesAndFields(s2);
}
}

public class Student {

private String _studentsPrivateField;

public Student() {
_studentsPrivateField = DateTime.Now.Ticks.ToString();
}

public void SeePrivatePropertiesAndFields(Student anotherStudent) {
//this seems like these should be private, even from the same class as it is a different instantiation
Console.WriteLine(anotherStudent._studentsPrivateField);
}
}

我能否对此的设计考虑/影响有一些想法。看来你不能向你的 sibling 隐藏信息。有没有办法将字段或成员标记为对同一类的其他实例隐藏?

最佳答案

有一种简单的方法可以确保这一点:

不要乱用同一类的其他实例的私有(private)成员。

说真的 - 你是编写 Student 代码的人。

关于C# 私有(private)成员可见性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2090285/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com