C#使用未声明泛型强制类型区分实现问卷跳转流程的问题
解决方案
这个问题可以解决,不需要更换整体方案,核心思路是通过非泛型基接口做类型擦除来兼容不同返回类型的后续链路,同时保留泛型实现的类型安全。
具体实现步骤
- 先定义无泛型参数的基接口,用于承载类型不固定的场景:
// 非泛型问题基接口,用于不需要知道具体答案类型的流程流转场景 public interface IPollQuestion { object Answer { get; } } // 非泛型链路基接口,统一不同泛型参数的链路类型 public interface IPollQuestionLink { IPollQuestion PreviousQuestion { get; } IPollQuestion NextQuestion { get; } bool Check(object previousAnswer); }
- 原有泛型接口继承基接口,显式实现基接口成员完成自动类型转换:
public interface IPollQuestion<TAnswer> : IPollQuestion { new TAnswer Answer { get; set; } IEnumerable<IPollQuestionLink> NextQuestionLinks { get; set; } // 显式实现基接口的Answer属性,无需手动处理类型转换 object IPollQuestion.Answer => Answer; } public interface IPollQuestionLink<TPreviousAnswer, TNextAnswer> : IPollQuestionLink { new IPollQuestion<TPreviousAnswer> PreviousQuestion { get; set; } new IPollQuestion<TNextAnswer> NextQuestion { get; set; } new Func<TPreviousAnswer, bool> Check { get; set; } // 显式实现基接口成员,自动完成类型校验和转换 IPollQuestion IPollQuestionLink.PreviousQuestion => PreviousQuestion; IPollQuestion IPollQuestionLink.NextQuestion => NextQuestion; bool IPollQuestionLink.Check(object previousAnswer) => Check((TPreviousAnswer)previousAnswer); }
业务场景适配示例
你提到的年龄、饮酒相关问题可以直接按原有逻辑实现,完全适配新的接口定义:
// 问题实例 var ageQuestion = new PollQuestion<bool> { /* 问题配置:是否年满18岁 */ }; var drinkQuestion = new PollQuestion<bool> { /* 问题配置:是否饮酒 */ }; var drinkCountQuestion = new PollQuestion<int> { /* 问题配置:每周饮用多少杯酒精饮品 */ }; // 链路实例 var ageToDrinkLink = new PollQuestionLink<bool, bool> { PreviousQuestion = ageQuestion, NextQuestion = drinkQuestion, Check = answer => answer == true }; var drinkToCountLink = new PollQuestionLink<bool, int> { PreviousQuestion = drinkQuestion, NextQuestion = drinkCountQuestion, Check = answer => answer == true }; // 关联问题和链路 ageQuestion.NextQuestionLinks = new[] { ageToDrinkLink }; drinkQuestion.NextQuestionLinks = new[] { drinkToCountLink };
方案优势
- 完全兼容你原本的设计思路,不需要调整整体架构
- 编写具体问题、链路逻辑时仍保留泛型的编译期类型安全,不会出现类型匹配错误
- 流程流转时直接调用非泛型基接口的
Check方法即可判断跳转逻辑,使用成本极低
内容的提问来源于stack exchange,提问作者JansthcirlU
相关产品推荐
相关产品推荐

