C#类成员访问权限疑问:私有成员能否被其他类访问?
关于C# Book类封装的问题解答
首先直接回答你的核心问题:
- 第一个示例里的
Title、Author这些成员,因为没加访问修饰符,在C#里默认是**私有(private)**的,其他类完全无法访问这些成员——哪怕构造函数是public,只能让其他类创建Book的实例,但实例里的这些字段外部既读不到也改不了。
两个示例的核心区别
第一个示例的访问权限
class Book // 默认是internal,仅当前程序集可访问 { string Title = null; // 默认private,仅Book类内部可访问 string Author = null; int Year = 0; string CoverType = null; public Book(string aTitle, string anAuthor, int aYear, string aCoverType) { Title = aTitle; Author = anAuthor; Year = aYear; CoverType = aCoverType; } }
这个写法里,其他类只能通过new Book(...)创建对象,但创建后根本碰不到Title这些字段,相当于实例的数据完全对外封闭。
第二个示例的访问权限
public class Book // 公开类,任何程序集都能访问 { public string Title = null; // 公开字段,外部可直接读写 public string Author = null; public int Year = 0; public string CoverType = null; public Book(string aTitle, string anAuthor, int aYear, string aCoverType) { Title = aTitle; Author = anAuthor; Year = aYear; CoverType = aCoverType; } }
这个写法里,外部类可以直接写book.Title = "新书名"或者读取var author = book.Author,完全没有访问限制。
C#里的封装惯例
C#和C++一样重视信息隐藏(封装),但不推荐直接暴露public字段,而是更推荐用**属性(Property)**来实现封装,比如:
public class Book { // 自动属性,编译器会自动生成私有备份字段 public string Title { get; set; } public string Author { get; set; } public int Year { get; set; } public string CoverType { get; set; } public Book(string title, string author, int year, string coverType) { Title = title; Author = author; Year = year; CoverType = coverType; } }
如果需要更严格的控制(比如Year不能是负数),可以改成带私有字段的属性:
public class Book { private int _year; public string Title { get; set; } public string Author { get; set; } public int Year { get => _year; set { if (value <= 0) throw new ArgumentOutOfRangeException(nameof(value), "年份不能小于等于0"); _year = value; } } public string CoverType { get; set; } public Book(string title, string author, int year, string coverType) { Title = title; Author = author; Year = year; CoverType = coverType; } }
这种方式既保留了封装性(可以在属性里加逻辑),又给外部提供了简洁的访问接口,后续修改内部逻辑时不需要改动外部代码,这才是C#里的最佳实践。
内容的提问来源于stack exchange,提问作者Mr.Longbottom
相关产品推荐
相关产品推荐

