简体   繁体   English

受保护的内部构造函数

[英]Protected internal constructor

I have a class ClassA that is a base class of other classes. 我有一个ClassA类,它是其他类的基类。 I want this class constructor to be internal and protected so that it can't be inherited and instantiated from outside of my assembly (I can't make it sealed because I have other internal classes inheriting from it, you can see my other related question here ) so I modified it to be like this: 我希望这个类构造函数是内部的并且受保护,以便它不能从我的程序集外部继承和实例化(我不能使其密封,因为我还有其他内部类继承自它,您可以看到我的其他相关问题在这里 ),因此我将其修改为:

public abstract ClassA{
    internal protected ClassA(){
    }
}

I have been told that this won't work as the combination internal protected is interpreted as internal OR protected which apparently makes the constructor only protected :( (visible from the outside) 有人告诉我这是行不通的,因为internal protected的组合被解释为internal OR protected ,这显然使构造函数仅protected ((从外部可见)

Questions 问题

  1. If that is true, why is internal protected interpreted as internal OR protected and not as internal AND protected ? 如果是这样,为什么将internal protected解释为internal OR protected而不是internal AND protected
  2. Is there a way I can declare a constructor internal and protected? 有没有一种方法可以声明内部构造函数并使其受保护?

Specifying internal is enough. 指定内部就足够了。

It's an abstract class - it's implied that its constructor is protected because you can't make an instance of it - you can do nothing BUT inherit it. 这是一个抽象类-它暗示其构造函数受到保护,因为您无法创建它的实例-您无法做任何事情但要继承它。

If you specify the constructor as internal it will be visible for all classes in your assembly and will not be visible to classes outside of it, which is exactly what you want to achieve. 如果将构造函数指定为内部构造函数,则它将对程序集中的所有类可见,而对外部的类则不可见,这正是您要实现的目标。 In short if a constructor or a class member of class A is: 简而言之,如果类A的构造函数或类成员为:

  • Protected - visible to all classes that inherit from A in its and in any other assembly 受保护的 -对在其及其任何其他程序集中继承自A的所有类可见
  • Internal - visible to all classes in class A's assembly 内部 -对A类的程序集中的所有类可见
  • Protected Internal - visible to all classes that inherit from A in its and in any other assembly and to all classes in A's assembly 受保护的内部 -对从A及其任何其他程序集中继承的所有类以及A的程序集中的所有类可见

So in you case you only need to specify the constructor as internal. 因此,在这种情况下,您只需要将构造函数指定为内部构造函数即可。

Did you try ? 你试过了吗 ?

Msdn tell us that MSDN告诉我们

Constructors can be marked as public, private, protected, internal, or protected internal. 构造函数可以标记为公共,私有,受保护,内部或受保护的内部。

http://msdn.microsoft.com/en-us/library/ms173115%28v=vs.100%29.aspx http://msdn.microsoft.com/zh-cn/library/ms173115%28v=vs.100%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM