类是私有的,成员是公开的,其范围是什么?

时间:2018-10-30 05:41:23

标签: c#

如果类声明为私有,并且其成员是公开,那么相关类的可访问性是什么?

3 个答案:

答案 0 :(得分:1)

如果私有类实现某些接口,则可以通过该接口访问公共方法。这是一段代码:

public interface ITest
{
    void Test();    
}

public class Program
{
    public static void Main()
    {
        ITest nestedProgram = new NestedProgram();
        AnyOtherClass otherClass = new AnyOtherClass();
        otherClass.AnyMethod(nestedProgram);
    }

    private class NestedProgram : ITest
    {
        public void Test()
        {
            Console.WriteLine("Test method invoked");
        }
    }
}

public class AnyOtherClass
{
    // won't compile
    // public void AnyMethod(Program.NestedProgram test)
    public void AnyMethod(ITest test)
    {
        // won't compile
        //ITest nestedProgram = new Program.NestedProgram();
        test.Test();
    }
}

答案 1 :(得分:0)

访问修饰符是用于指定成员或类型的声明可访问性的关键字。

公共修饰符

public关键字是类型和类型成员的访问修饰符。公共访问是最宽松的访问级别。

访问公共成员没有任何限制。

可访问性

  

可以被该类的对象访问

     

可以被派生类访问

私人访问权限是最低的访问权限级别。

私有成员只能在声明它们的类或结构体中访问。

可访问性

  

不能被对象访问。

     

派生类无法访问。

现在,如果将该类声明为私有并且其成员是公共的,那么让我们来找到确切的答案,因为无法继承私有类,所以成员的可访问性级别将保留在该类之内。

答案 2 :(得分:0)

该类就是您声明的类。类声明中的“ private”修饰符对嵌套类很重要,但是没有阻止其嵌套的类使用其公共成员的方法。我认为这两者并不是特别相关,因为它们的目标略有不同(一个是类本身对实例化的可见性,可以在何处进行引用,另一个是可以访问哪些成员)。

也请考虑以下示例:

public interface ITest
{
    void TestMethod();
}

public static class TestFactory
{
    private class Test: ITest
    {
        public void TestMethod() { }
    }

    public static ITest CreateTest()
    {
        return new Test();
    }
}

示例:

TestFactory.Test a = new TestFactory.Test(); // doesn't work because the class is private
TestFactory.Test b = null; // also doesn't work because the class is private
ITest c = null; // works, the interface is public
ITest d = TestFactory.CreateTest(); // works, because the interface is public and CreateTest is declared to return the interface.

在此示例中,只有TestFactory可以看到该类以创建其实例。另一方面,返回值是public接口,它声明实现者应该具有公共方法TestMethod();

在这种情况下,该方法必须是公开的。尽管只有TestFactory可以直接实例化并查看类,但仍可以通过接口(或基类)公开它。

无论如何,最好看看docs

相关问题