抽象类的可访问性不一致 [英] Inconsistent accessibility with abstract classes

查看:99
本文介绍了抽象类的可访问性不一致的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个内部抽象类 InternalClassBase 和两个(也是内部)类 InternalClass1 InternalClass2 ,继承自 InternalClassBase

I have an internal abstract class InternalClassBase and two (also internal) classes InternalClass1 and InternalClass2, which inherit from InternalClassBase.

我还有一个公共抽象类 PublicClassBase 和两个(也是公共的)类 PublicClass1 PublicClass2 ,该继承自 PublicClassBase

I also have a public abstract class PublicClassBase and two (also public) classes PublicClass1 and PublicClass2, which inherit from PublicClassBase.

PublicClassBase 具有受保护成员 XXX 类型为 InternalClassBase 的成员,因此都 PublicClass1 并且 PublicClass2 可以使用它。

The PublicClassBase has a protected member XXX of type InternalClassBase, so both PublicClass1 and PublicClass2 can use it.

这是我的代码:

internal abstract class InternalClassBase { }
internal class InternalClass1 : InternalClassBase { }
internal class InternalClass2 : InternalClassBase { }

public abstract class PublicClassBase
{
    protected InternalClassBase XXX;  // this is where the error happens
}
public class PublicClass1 : PublicClassBase { }
public class PublicClass2 : PublicClassBase { }

为什么 PublicClassBase 包含 XXX 成员我的榜样?我认为 XXX 仅在 PublicClassBase PublicClass1 和 PublicClass2 ,但不在其范围之外。

Why can't PublicClassBase contain the XXX member in my example? I thought that XXX would only be visible within PublicClassBase, PublicClass1 and PublicClass2, but not outside of it.

我还认为我了解访问修饰符,但显然我不要:)

I also thought that I understand access modifiers, but obviously I don't :)

编辑-错误发生在PublicClassBase内部的XXX声明中,并且异常消息是:不一致的可访问性:字段类型'ClassLibrary2.InternalClassBase'较少比字段'ClassLibrary2.PublicClassBase.XXX'更易于访问,但是如何保护它而不是内部?

Edit - the error happens at declaration of XXX inside PublicClassBase, and the exception message is: Inconsistent accessibility: field type 'ClassLibrary2.InternalClassBase' is less accessible than field 'ClassLibrary2.PublicClassBase.XXX', but how can protected be more accessible then internal?

推荐答案

想象一下声明了不同于示例中的一种类型的程序集 other ,则声明了从 PublicClassBase PublicClass3 $ c>。 XXX 字段应该在 PublicClass3 中可见,因为它是受保护的,但是该字段的类型是内部的,因此同时,它应该在 PublicClass3 中不可见。

Imagine that in an assembly other than the one types from your example are declared, you declare class PublicClass3 that inherits from PublicClassBase. The field XXX should be visible from PublicClass3, since it is protected, but the type of the field is internal, so at the same time, it should not be visible from PublicClass3.

显然,

您可以通过将字段设为 private 来解决此问题,也可以设置为 PublicClassBase 及其子对象 internal

You can solve this either by making your field private, or making PublicClassBase and its children internal.

这篇关于抽象类的可访问性不一致的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆