How to limit subclassing of public abstact class to types in same assembly and thus allow protected members typed to internal types

江枫思渺然 提交于 2019-12-01 17:48:15

The CLR provides a FamilyAndAssembly accessibility which will do what you want, but there isn't the syntax in C# to use it.

The workaround is to make the variable field internal, and you'll have to trust the code in your assembly to not access it inappropriately.

You can also make the constructor of PublicBaseClass internal, so only your assembly can instantiate it. That way, only your classes can inherit off it (even if the class itself is public)

The cleanest way to deal with this is the use of public interfaces and private classes. If your refactoring existing code this is not always an option. One easy way to ease the pain of that conversion is to use a public abstract class instead of an interface and expose a static factory method.

Example:

public abstract class MyClass
{
    public static MyClass New()
    { return new InternalMyClass(); }
}

class InternalMyClass : MyClass
{ }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!