简体   繁体   English

受保护字段中的 C# 内部类型

[英]C# internal types in protected fields

I am trying to write a class library as following:我正在尝试编写一个类库,如下所示:

namespace Test
{
    class Field
    { 
    }

    public abstract class SomeClass
    {
        protected Field field;  //Inconsistent accessibility: field type 'Field' is less accessible than field 'SomeClass.field'
    }

    public class SomeDerivedClass1:SomeClass
    {
    }

    public class SomeDerivedClass2:SomeClass
    {
    }
}

Rules:规则:

  1. I do not want to make Field a protected subclass of SomeClass , because it is used by other classes;我不想让Field成为SomeClass的受保护子类,因为它被其他类使用;
  2. I do not want to make Field visible outside of Test namespace, because it's breaks encapsulation;我不想让FieldTest命名空间之外可见,因为它破坏了封装;
  3. I need inheritance, because SomeDerivedClass1 and SomeDerivedClass2 share a lot of code.我需要继承,因为SomeDerivedClass1SomeDerivedClass2共享很多代码。

Is any workaround for this problem without breaking any of these rules?在不违反任何这些规则的情况下,是否有解决此问题的方法?

You can use the new private protected modifier .您可以使用新的private protected修饰符 This is the equivalent of internal AND protected .这相当于internal AND protected

Not to be confused with protected internal which is protected OR internal不要与protected internal protectedinternal protected internal混淆

public abstract class SomeClass
{
    private protected Field field;
}

It is still visible in the same assembly outside the namespace though.尽管如此,它在命名空间外的同一个程序集中仍然可见。

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

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