如何让泛型扁平化方法仅支持同具体实现嵌套类型编译?
泛型扁平化方法的编译期约束实现
问题背景
现有如下递归泛型接口及具体实现:
public interface IInterface<T, U> where U : IInterface<T, U> {} public class ConcreteA<T> : IInterface<T, ConcreteA<T>> {} public class ConcreteB<T> : IInterface<T, ConcreteB<T>> {}
需要实现一个扩展方法Flatten,仅支持同一具体类嵌套两层的结构(如ConcreteA<ConcreteA<T>>),将其转换为ConcreteA<T>;同时要在编译期直接拒绝混合实现的情况(如ConcreteB<ConcreteA<T>>),避免运行时反射检查。
原实现的Flatten方法无法做到编译期约束:
public static S Flatten<R, S, T>(this R nested) where R : IInterface<S, R> where S : IInterface<T, S> { // 扁平化逻辑 }
解决方案
通过绑定外层与内层的具体实现类为同一个泛型参数,在方法签名层面直接限定输入类型,实现编译期约束:
public static C<T> Flatten<T, C>(this C<C<T>> nested) where C : IInterface<T, C> { // 此处编写扁平化逻辑 // 示例:假设嵌套实例内部持有内层对象,可直接返回 // return nested.InnerValue; return default; }
约束原理
- 泛型参数
C明确指定了嵌套两层的具体实现类,强制外层和内层必须是同一个类型 - 方法接收者类型
C<C<T>>直接限定了输入必须是同一类嵌套两层的结构 - 约束
where C : IInterface<T, C>确保C符合原接口的递归泛型要求
调用验证
合法调用(编译通过):
ConcreteA<ConcreteA<int>> nestedA = new(); ConcreteA<int> flattenedA = nestedA.Flatten<int, ConcreteA>();非法调用(编译失败):
// 混合实现的嵌套,编译报错:无法将ConcreteB<ConcreteA<int>>转换为ConcreteB<ConcreteB<int>> ConcreteB<ConcreteA<int>> mixedNested = new(); mixedNested.Flatten<int, ConcreteB>();
内容的提问来源于stack exchange,提问作者Totofofo
相关产品推荐
相关产品推荐

