首页 > 解决方案 > Extending the base class of a hierarchy tree

问题描述

How can I extend a base class of a hierarchy tree to provide extra functionality based on encapsulated (protected values) where all children of this base class can benefit from these extensions?


Consider the following hierarchy of types.

Hierarchy

The dots indicate more classes that introduce extra types (<T1, T2, T3>, then <T1, T2, T3, T4> etc).

If you want to use this code, you should extend one of the lower classes (either SimpleValidator or SectionedValidator) and insert the model(s) you want to validate as the type argument(s).

Now a user might decide they want some extra functionality on the Validator class, i.e. the base class. But since everything is encapsulated, you cannot create extension methods since they can only access public properties/methods.

Extending Validator by inheriting from it is also a no-go because that would mean users will have to go through the whole boiler-plating themselves by writing all the typed variants again.

I'd ideally like to inject a class in-between Validator and Validator<...>, but I don't think this is possible in C# in an elegant/user-friendly way.

标签: c#inheritanceextend

解决方案


推荐阅读