简体   繁体   中英

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;
  2. I do not want to make Field visible outside of Test namespace, because it's breaks encapsulation;
  3. I need inheritance, because SomeDerivedClass1 and SomeDerivedClass2 share a lot of code.

Is any workaround for this problem without breaking any of these rules?

You can use the new private protected modifier . This is the equivalent of internal AND protected .

Not to be confused with protected internal which is protected OR internal

public abstract class SomeClass
{
    private protected Field field;
}

It is still visible in the same assembly outside the namespace though.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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