C#访问修饰符

C#访问修饰符

public

public是最常用的访问修饰符,它可以让成员在程序中的任何位置被访问。当成员被标记为public时,任何类、方法或对象都可以访问该成员。

public class MyClass
{
    public int MyPublicField;
    
    public void MyPublicMethod()
    {
        Console.WriteLine("This is a public method.");
    }
}

MyClass obj = new MyClass();
obj.MyPublicField = 10;
obj.MyPublicMethod(); // Output: "This is a public method."


private

private是访问修饰符中最严格的,它只允许类的成员访问。当成员被标记为private时,只有在该类的定义内部才能访问该成员。在继承中,private成员不能被子类访问。

public class MyClass
{
    private int MyPrivateField;
    
    private void MyPrivateMethod()
    {
        Console.WriteLine("This is a private method.");
    }
}

MyClass obj = new MyClass();
obj.MyPrivateField = 10; // Error: MyPrivateField is inaccessible due to its protection level
obj.MyPrivateMethod(); // Error: MyPrivateMethod is inaccessible due to its protection level


protected

protected访问修饰符允许类的成员和派生类的成员访问。当成员被标记为protected时,只有在该类的定义内部或其派生类中才能访问该成员

public class MyClass
{
    protected int MyProtectedField;
    
    protected void MyProtectedMethod()
    {
        Console.WriteLine("This is a protected method.");
    }
}

public class MyDerivedClass : MyClass
{
    public void MyMethod()
    {
        MyProtectedField = 10;
        MyProtectedMethod();
    }
}

MyDerivedClass obj = new MyDerivedClass();
obj.MyMethod(); // Output: "This is a protected method."


internal

internal访问修饰符允许在同一程序集中的任何类访问成员。当成员被标记为internal时,只有在同一程序集中的任何类才能访问该成员。不同程序集的类不能访问internal成员。

internal class MyClass
{
    internal int MyInternalField;
    
    internal void MyInternalMethod()
    {
        Console.WriteLine("This is an internal method.");
    }
}

MyClass obj = new MyClass();
obj.MyInternalField = 10;
obj.MyInternalMethod(); // Output: "This is an internal method."


protected internal

protected internal是protected和internal的结合体。它允许在同一程序集中的任何类和派生类访问成员。当成员被标记为protected internal时,只有在同一程序集中的任何类和派生类才能访问该成员。

public class MyClass
{
    protected internal int MyProtectedInternalField;
    
    protected internal void MyProtectedInternalMethod()
    {
        Console.WriteLine("This is a protected internal method.");
    }
}

public class MyDerivedClass : MyClass
{
    public void MyMethod()
    {
        MyProtectedInternalField = 10;
        MyProtectedInternalMethod();
    }
}

MyDerivedClass obj = new MyDerivedClass();
obj.MyMethod(); // Output: "This is a protected internal method."

posted @ 2023-03-10 02:07  Wo_OD  阅读(99)  评论(0编辑  收藏  举报