在C#中受保护的访问说明符和受保护的内部有什么区别

访问说明符protected和C# internal protected什么区别?

Internal可以在组件中看到。

Protected的类可以从inheritance自定义它的类inheritance。

Protected internal可以在从定义它的类派生的程序集OR类型中看到(包括来自其他程序集的类型)。

请参阅: http : //msdn.microsoft.com/en-us/library/ba0a1yw2.aspx

从页面复制:

 public Access is not restricted. protected Access is limited to the containing class or types derived from the containing class. internal Access is limited to the current assembly. protected internal Access is limited to the current assembly or types derived from the containing class. private Access is limited to the containing type. 

protected表示只有当前类,从中派生的任何类都可以访问该成员。

internal表示当前程序集中的任何类都可以访问该成员。

protected internal基本上是指protected 即,从当前类(在任何程序集中)派生的所有类都可以访问该成员,就像当前程序集中的所有类一样。 这与许多开发人员所期望的相反 – protected internal意味着与protected internal相同(它没有)。

  • internal – 由同一程序集中的任何内容(.dll或.exe)可见。
  • protected – 任何子类都可以看到,无论它们在哪里。
  • internal protected – 无论身在何处,都可以在同一个程序集任何子类中查看。

杰夫马特菲尔德说“内部进一步降低可见度”的方式使其不清楚。 internalprotected的只是不同的可见性。 两者结合使得会员更加醒目。 没有显式访问修饰符的东西的默认可见性尽可能小。 添加任何访问修饰符始终会提高可见性。

internal protectedprotected internal ,与外部protected (来自当前组件外部)和内部public (来自同一组件内)相同。

受保护的内部受保护的访问说明符与inheritance的概念有关。

让我们举个例子来解释受保护受保护的内部

有两个命名空间,名为命名空间A命名空间B.

命名空间A中 ,有一个名为classA的类,它由一个名为accept()的方法组成,该方法使用受保护的访问说明符。

命名空间B中 ,还有另一个名为classB的类,它inheritance自命名空间A的 classA

现在在这个受保护的说明符的帮助下,我们可以访问命名空间BclassB中accept()方法。

但是当使用受保护的内部访问说明符时,这个概念是不正确的:如果命名空间AclassAaccept()函数使用受保护的内部访问说明符,则命名空间B的 classB无法访问它,因为accept()函数只能在同一名称空间中的inheritance类。

internal protected允许您从不是从同一对象派生的类访问同一程序集中的成员,但也允许您从另一个程序集访问成员时获得的标准受保护访问。 这是内部的 受保护,而不是内部和受保护(虽然CLR允许后者,C#不会)

为了更好地理解受保护和受保护的Internal.it之间的区别,最好首先了解受保护和内部之间的区别。

内部变量指的是同一个程序集。不能在不同的程序集中访问。 受保护的变量,如私有变量,但您可以在同一个程序集或不同程序集中的驱动类中访问。

  namespace InternalTest ----This namespace in assembly One { Public class A { B ol=new B(); Console.WriteLine(ol.x);//Output:5 Console.WriteLine(ol.y);//error will occured. Because protected is like Private variable } public class B { Internal int x=5; Protected int y=5; } } 

2)采取不同的assembly。

  using InternalTest; namespace InternalTest1 ----This namespace in assembly Two { Public class A1:B { Public void GetInternalValue() { return x; //error can't access because this is internal } Public void GetProtectedValue() { return y;//Work because it's protected } } public class C { } } 

从上面的例子中它清除你可以在同一个程序集中访问内部而不是在不同的程序集中。你可以说在同一个程序集中它看起来像公共变量。你可以通过创建类的对象来赋值

3)受保护的内部在同一组件中具有良好性,它看起来像公共变量。 在diifrent汇编中你使用像受保护的变量

您好您可以通过下表找到辅助function

受保护

如果该类声明为“protected”,则表示它可以由程序集中的子类以及程序集外部的子类访问。

内部

如果该类声明为“internal”,则表示它可以被程序集中的任何类访问。

受保护的内部

如果该类声明为“protected internal”,则意味着只能通过派生类在程序集中访问它。

Interesting Posts