相关疑难解决方法(0)

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

例如

BaseClass MyBase()
{
    public int Add(BaseClass next)
    {
        if (this is InheritedA && next is InheritedA)
            return 1;
        else if (this is InheritedA && next is InheritedB)
            return 2;
        else if (this is InheritedB && next is InheritedA)
            return 3;
        else if (this is InheritedB && next is InheritedB)
            return 4;      
     }
}
Run Code Online (Sandbox Code Playgroud)

where InheritedA,InheritedB是它的继承类.实际上,还有更多的Inherited类,并Add根据其操作数的顺序和类型返回不同的结果.

我正在考虑使用多态和重载来重写它,但是,它变得相当复杂,我必须引入一个帮助方法来解析任一端的类型.

例如

InheritedA myA()
{
    public override int Add(BaseClass next)
    {
        return next.AddTo(this);
    }
}
Run Code Online (Sandbox Code Playgroud)

现在我不得不把AddToBaseClass …

c# polymorphism overloading

6
推荐指数
2
解决办法
272
查看次数

标签 统计

c# ×1

overloading ×1

polymorphism ×1