C#私有成员可见性

Ara*_*and 13 c# private-members

我们的商业模式中有一个学生班.令我感到奇怪的是,如果我们操纵另一名学生的一名学生,学生的私人成员是可见的...这让我觉得有点不雅:)

   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);
      }
   }
Run Code Online (Sandbox Code Playgroud)

我可以对设计考虑因素/含义有所了解吗?您似乎无法隐藏兄弟姐妹的信息.有没有办法将字段或成员标记为对同一类的其他实例隐藏?

Ano*_*on. 9

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

不要乱用同一类的其他实例的私有成员.

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


Dar*_*ter 8

确保这一点的最简单方法是编程到接口,例如:

class Program
{
    static void Main(string[] args)
    {
        IStudent s1 = new Student();
        IStudent s2 = new Student();

        s1.ExamineStudentsMembers(s1);
    }
}

public interface IStudent
{
    void ExamineStudentsMembers(IStudent anotherStudent);
}

public class Student : IStudent
{
    private string _studentsPrivateMember;

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

    public void ExamineStudentsMembers(IStudent anotherStudent)
    {
        Console.WriteLine(anotherStudent._studentsPrivateMember);
    }
}
Run Code Online (Sandbox Code Playgroud)

由于ExamineStudentsMembers试图访问私有字段,因此将不再编译.

  • 这根本不会让私人成员看不到......它只是不访问它们。我可以在不添加接口的情况下`只是不访问它们`......或者在接口到位后,我仍然可以添加另一个采用 Student 参数的方法(`private ExamineStudentDirectly(Student anotherStudent) { }`),该方法确实访问其他实例的私有成员。 (2认同)

小智 5

如果您正在编写该类,则可以完全控制它,因此如果您不希望一个对象能够修改另一个对象,请不要写入该功能.

类通常在其他实例中使用私有变量来实现有效的比较和复制功能.