当前位置: 首页 > 编程语言 > C#

如何使用多态+重载来改进这个方法来减少IS(类型检查)?分享

时间:2023-04-11 02:01:44 C#

这种做法如何改进使用多态+重载来减少IS(类型检查)?例如BaseClassMyBase(){publicintAdd(BaseClassnext){if(thisisInheritedA&&nextisInheritedA)return1;elseif(thisisInheritedA&&nextisInheritedB)return2;elseif(thisisInheritedB&&nextisInheritedA)return3;elseif(thisisInheritedB&&nextisInheritedB)return4;其中InheritedA和InheritedB是它继承自的类。事实上,Inherited类还有很多,Add会根据其操作数的顺序和类型返回不同的结果。我正在考虑使用多态性和重载重写它,但是,它变得相当复杂,我必须引入一个辅助方法来解析两端的类型。例如InheritedAmyA(){publicoverrideintAdd(BaseClassnext){returnnext.AddTo(this);现在我必须将AddTo放入BaseClass并在继承类中覆盖它。InheritedAmyA(){publicoverrideintAddTo(InheritedAnext){return1;}publicoverrideintAddTo(InheritedBnext){return3;}}BaseClassmyBase(){publicabstractintAdd(BaseClassnext);publicabstractintAddTo(InheritedAnext);publicabstractintAddTo(InheritedBnext);}有没有更好的办法?您正在实施的模式称为双重虚拟分派。单个虚拟分派根据接收者的运行时类型和参数的编译时类型选择调用哪个方法。这是传统的虚拟调度:抽象类动物{}类老虎:动物{}类长颈鹿:动物{}类B{公共虚拟无效M(老虎x){}公共虚拟无效M(动物x){}}类D:B{publicoverridevoidM(Tigerx){}publicoverridevoidM(Animalx){}}...Bb=whatever;动物a=newTiger();bM(a);调用了哪个方法?BM(Tiger)和DM(Tiger)未被选中;我们根据参数的编译时类型拒绝它们,即Animal。但是我们在运行时根据是newB()还是newD()来选择调用BM(Animal)还是DM(Animal)newD()。doublevirtualdispatch根据两个事物的运行时类型来选择调用哪个方法。如果C#支持双重虚拟分派,而它不支持,那么运行时分派将转到BM(Tiger)或DM(Tiger),即使参数的编译时类型是Animal。但是,C#4支持动态调度。如果你说dynamicb=whatever;动态a=newTiger();bM(a);那么M的分析将完全在运行时使用b和a的运行时类型完成。这明显更慢,但它有效。或者,如果你想做doublevirtualdispatch,尽可能在编译期做分析,那么标准的做法就是实现visitorpattern,网上随便找找。正如评论中所建议的那样,如果您能够为每个推导分配一个常量值,则可以构建比我在此处描述的更简洁的实现,只需要一个名为Value或类似的虚拟属性来添加成为。假设这不是一个选项,您可能需要考虑在基类级别的预计算结果,描述您为每个组合分配的值。随着集合的增长,这可能会崩溃并变得容易出错且乏味,因此我建议仅在您希望维护非常小的集合时才考虑这一点。在我的基本示例中,我使用字典来保存集合并对组合进行硬编码。根据您的评论,似乎没有任何基本的算术规则适用,所以我将它们留在这里作为约束。如果结果值没有实际意义并且您只是递增它,您可以考虑使用反射来构建结果集以拉取派生类并考虑每个组合。以上就是C#学习教程:如何使用多态+重载来改进这个方法来减少IS(类型检查)?如果分享的内容对你有用,需要了解更多C#学习教程,希望你多多关注——publicclassBaseClass{privatestaticreadonlyDictionaryaddResults=newDictionary();staticBaseClass(){addResults.Add(CreateKey(typeof(ChildA),typeof(ChildA)),1);addResults.Add(CreateKey(typeof(ChildA),typeof(ChildB)),2);addResults.Add(CreateKey(typeof(ChildB),typeof(ChildA)),3);addResults.Add(CreateKey(typeof(ChildB),typeof(ChildB)),4);}publicstaticintCreateKey(Typea,Typeb){return(String.Concat(a.Name,b.Name).GetHashCode());}publicintAdd(BaseClassnext){varresult=default(int);if(!addResults.TryGetValue(CreateKey(this.GetType(),next.GetType()),outresult)){thrownewArgumentOutOfRangeException("未知操作数组合");}返回结果;}}publicclassChildA:BaseClass{}publicclassChildB:BaseClass{}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处: