困惑:内部,受保护和受保护的内部

Pri*_*kar 13 c# oop

可能重复:
'protected'和'protected internal'有什么区别?
Public,Private,Protected和Nothing之间有什么区别?

代码如下所述:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testanotherlib
{
    public class A
    {
        internal void InternalDisplay()
        {
            Console.WriteLine("Internal Display Method.");
        }

        protected void ProtectedDisplay()
        {
            Console.WriteLine("Protected Display Method.");
        }

        protected internal void ProtectedInternalDisplay()
        {
            Console.WriteLine("ProtectedInternal Display Method.");
        }

        public void PublicDisplay()
        {
            Console.WriteLine("Public Display Method.");
        }
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace testanotherlib
{
    public class B : A
    {
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using testanotherlib;
namespace testlib
{
    public class C:A
    {
    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using testlib;
using testanotherlib;

namespace testapp
{
    class Program
    {
        static void Main(string[] args)
        {
            B objB = new B();
            C objC = new C();
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我试图了解内部,受保护和受保护内部之间的区别.为此,我使用上面的代码创建了一个示例.

在类库项目testanotherlib中,我有类A和类B.在类库项目testlib中,我有类C.程序类在一个单独的控制台应用程序中.在Program类的主要方法中,我为类B(objB)和类C(objC)创建了对象.对于objB和objC,只能访问A类的公共方法.我被期待B级所有A级方法都可以访问.请帮助我理解这一点.如果您需要有关该项目的任何其他信息,请随时问我.

此致,Priyank

Chr*_*ler 14

可以使用访问修饰符指定以下五个辅助功能级别:

public:访问不受限制.

protected:访问仅限于从包含类派生的包含类或类型.

内部:访问仅限于当前程序集.

protected internal:访问仅限于从包含类派生的当前程序集或类型.

private:访问仅限于包含类型.

直接来自微软的MSDN库.

  • 你可能是对的.请立即通知微软!! (5认同)

Ter*_*kel 5

internal

仅在当前和友好组件中可见.

protected

仅在继承的类中可见A.

protected internal

在继承的类中可见A.并且在当前和友好组件中也可见.


归档时间:

查看次数:

15608 次

最近记录:

13 年,6 月 前