开发者

Enforce inheritance in .net

开发者 https://www.devze.com 2023-01-27 05:06 出处:网络
Is it possible to enforce inheritance in .net? For example, I have a class library project which contains a base class say \"BaseEntity\". I have 3 classes say \"EntityA\", \"En开发者_如何学CtityB\"

Is it possible to enforce inheritance in .net?

For example, I have a class library project which contains a base class say "BaseEntity". I have 3 classes say "EntityA", "En开发者_如何学CtityB" and "EntityC" and all these classes inherit from this base class. Now when I create another class in this project, .net should give me a compile time error that this class does not inherit from the class "BaseEntity".


You can't force the C# compiler to make every class within a project inherit from a particular other class, no. Nor should you. What if you want to create some helper class, or other non-entity class? Why should everything in the project be an entity?

Now two ways you can force inheritance:

  • You can make BaseEntity an abstract class, so that whenever you deal with an instance of BaseEntity you're really dealing with an instance of some derived class.
  • You can write a generic type or method using a type parameter with a constraint such that the type argument must be BaseEntity or a derived class:

    public void EntityLoader<T> where T : BaseEntity
    

Neither of those are what you're asked for, but they're what's available.


If you really want to do this (and I think Jon Skeet is right when he says you should not), you could write a helper command line utility which loads the specific assembly, tests your inheritance rules by using reflection. To get a compile time error, call this program within a postbuild event of your project.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号