C#私有成员的可视性 [英] C# Private members visibility
问题描述
我们有我们的商业模式一个学生类。事情让我觉得奇怪,如果我们从另一个学生操纵一个学生,学生私有成员可见......这给我的印象有点不雅:)
We have a Student class in our business model. something struck me as strange, if we are manipulating one student from another student, the students private members are visible... this strikes me as a little indecent :)
class Program {
static void Main(string[] args) {
Student s1 = new Student();
Student s2 = new Student();
s1.ExamineStudentsMembers(s2);
}
}
public class Student {
private String _studentsPrivateMember;
public Student() {
_studentsPrivateMember = DateTime.Now.Ticks.ToString();
}
public void ExamineStudentsMembers(Student anotherStudent) {
//this seems very wrong
Console.WriteLine(anotherStudent._studentsPrivateMember);
}
}
我可以对设计考虑/影响的几点思考这个的。看来你不能隐藏你的兄弟姐妹信息。有没有一种方法来标记字段或成员来自同一类的其他实例隐藏?
Can i have some thoughts on the design considerations/implications of this. It seems that you can't hide information from your siblings. Is there a way to mark a field or member as hidden from other instances of the same class?
推荐答案
有一个简单的方法来确保这一点:
There's an easy way to ensure this:
不要在同一类的其他实例的私有成员勾搭
Don't mess around with private members of other instances of the same class.
严重 - 你是一个写学生
代码
Seriously - you're the one writing the Student
code.
这篇关于C#私有成员的可视性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!