Bootstrap

【C#】访问修饰符public、protected、private、internal的区别

public 公有访问,不受任何限制。

private 私有访问,只限于本类成员访问(子类、父类、实例都不能访问)。

protected 保护访问,只限于本类、子类、父类访问(实例不能访问)。

internal 内部访问,只限于本命名空间(程序集)内访问,其他命名空间(程序集)内不能访问,程序集就是命名空间。

protected internal 保护访问 和 内部访问的并集,符合任意一条都可以访问。

表格展示以上定义

本类子类实例
private 私有访问
protected 保护访问
public 公有访问
不同命名空间 namespace
internal 内部访问
public 公有访问

代码解释 protected 本类子类可访问

public class Country
{
    //一、本类成员访问protected类型
    //(protected后面加上static,是由于初始值设定必须是静态字段)
    protected static string _continent = "亚洲";
    public string continent { get; set; } = _continent;

    protected string _country = "中国";
}
public class Address: Country
{
	//二、子类访问父类的protected类型
    public string country => _country;    
}

 代码解释 private 本类可访问(两种写法)

public class Person
{
    //一、本类成员访问private类型
    //(其中 => 是简化的 get 访问器)
    private int _gender = 1;
    public string gender => _gender == 1 ? "Male" : "Female";
              
    //(其中包含get访问器,字段可读,用于较为复杂的计算属性)
    private int _age = 100;
    public string age
    {
        get
        {
            return $"{_age} years old";
        }
    }
}
;