How can I create a class A in C#, where A can only be inherited by B, C, D?
There i开发者_开发知识库s some mechanism to allow a class to be inherited by N classes only in C#?
You may put it and it's derived classes in a separate assembly, and declare the constructor of the base class as internal
. That way although you could inherit from it in a different assembly, but you wouldn't be able to instantiate any derived class.
No, but you can always make the constructor throw an exception if it exceeds the limit.
// can be inherited only by classes in the same assembly
public abstract class A
{
protected internal A() { }
}
// can't be inherited
public sealed class B : A
{
}
Just for my personal edification, I'd like to know more about the business context which make such a design choice desirable, since my first thougt at reading the title was "Oh, very very bad idea ! A base class is NEVER supposed to know anything (and worse : to rule) its derived classes".
You can make the class A abstarct and inherit it in any number of classes..
精彩评论