【问题标题】:I have a protected class that I'd like to be a property inside a public class, but accessible to derived classes in the same assembly我有一个受保护的类,我想成为公共类中的一个属性,但同一程序集中的派生类可以访问
【发布时间】:2012-07-24 07:04:51
【问题描述】:

我正在使用 C# 4。

cmets 解释了类的目的以及为什么它们的结构是这样的。

/// <summary>
/// I want this internal just to reduce the number of publicly
/// accessible classes in this assembly.  I don't want people to
/// come after me to even spend time reading about this class,
/// since it won't help them unless they're modifying, and not
/// using this assembly.
/// </summary>
internal class MyInternalClass
{
}

/// <summary>
/// This class is an initialization class for tests.  This is the
/// base class for other initialization classes so that I can have 
/// a tree-like structure of method calls.  This needs to be
/// public because it is the base class of a derived class that needs
/// to be public.
/// </summary>
public class MyPublicClass
{
    protected internal MyInternalClass MyInternalProperty;
}

/// <summary>
/// This class is a test class that tests a particular initialization
/// class.  This class needst to be public, else the Unit Testing 
/// framework will not execute its methods.
/// </summary>
public class MyInheritedPublicClass : MyPublicClass
{
}

谁能告诉我为什么我收到上述代码的可见性不一致错误?

据我了解,这里是 C# 中可见性修饰符的含义:

public:任何地方的每个人都可以看到和访问它,而无需任何形式的反射黑客。

private:这只能在它声明的类的范围内访问。派生类和同一命名空间和程序集中的其他类看不到这一点。

protected:这只能在它声明的类和任何派生类的范围内访问,无论程序集或命名空间如何,只要该类是公共的。如果类是内部的,那当然会进一步限制可以看到这个属性的类。

internal:只有同一程序集中的实体才能访问。

我认为protected internal 修饰符的作用类似于维恩图中protectedinternal 的交集——它只能被位于同一程序集中并且是所述类的子类的实体访问属性/方法/构造函数/字段/任何存在的地方。鉴于我的信念,我认为前面的代码应该可以编译。

【问题讨论】:

    标签: c# visibility internal protected


    【解决方案1】:

    protected internal 不是protectedinternal交集,它是一个联合,这意味着protected internal 属性将对所有人可见阶级的后代,无论他们在哪个议会。

    参考:http://msdn.microsoft.com/en-us/library/ms173121.aspx

    【讨论】:

    • 好吧,那么我会接受一个问题(一旦允许我接受;没有足够的时间过去):我如何到达交叉路口?
    • 根据 Richter 的说法,在 C# 中没有办法做到这一点。
    • 谢谢!我只是在内部查找了受保护的交叉联合,现在我知道了行话,发现了一些资源。鉴于交叉点提供的好处有限,而且微软的资源有限,我很高兴他们没有实施它。通过增加可见性,我可以轻松地在我的代码中继续前进;我更感兴趣的是了解更多关于 C# 以及它为什么无法编译的信息。再次感谢!
    猜你喜欢
    • 2021-12-04
    • 2018-04-17
    • 2011-12-25
    • 2018-05-07
    • 1970-01-01
    • 1970-01-01
    • 2011-12-08
    • 2023-04-09
    • 2022-07-20
    相关资源
    最近更新 更多