简体   繁体   English

覆盖重载 C#

[英]Overriding overloads C#

Ok, so I've already solved this but I want to ask/share what you guys think.好的,所以我已经解决了这个问题,但我想问/分享你们的想法。

I have a base class with 2 overloads for a method, for instance例如,我有一个带有 2 个方法重载的基类

public class Entity{
    public virtual bool Save() {
          //ReallySave()...
    }

    public virtual int Save(string someParam){
       //also ReallySave()...
    }
}

and I have a derived class, in which I would like to override whatever save() method I feel like overriding, for instance我有一个派生类,我想在其中覆盖我想要覆盖的任何 save() 方法,例如

class Person {
     override int Save(string someParam){
           console.log(someParam)
           base.Save(someParam);
     }
}

Now the problem is, somewhere else, I wan to call现在的问题是,在别处,我想打电话

person.Save();

or或者

 person.Save("hello");

but I have no way to know (nor should I) which overload is overriden.但我无法知道(也不应该)哪个重载被覆盖。 This code falls due to its combination of overridable overloaded methods, since calling save() would not go into the overriden method.这段代码由于其组合了可覆盖的重载方法而失败,因为调用 save() 不会进入覆盖方法。

So I did some trickery to make sure, at the base level, each base method calls the other, something like the "chain of responsability" pattern.所以我做了一些诡计,以确保在基本级别,每个基本方法调用另一个,类似于“责任链”模式。

An example of the modifyed base class would be修改后的基类的一个例子是

public class Entity{

    private bool WithParamsMethodCalled = false;
    private bool NoParamsMethodCalled = false;
    public virtual bool Save() {
          NoParamsMethodCalled  = true;
          if(!WithParamsMethodCalled ) { Save(""); }
          //ReallySave()...
    }

    public virtual int Save(string someParam){
           WithParamsMethodCalled = true;
          if(!NoParamsMethodCalled ) { Save(); }
          ///no need to call ReallySave() here
    }
}

Now the question: Is there a better way to do this?现在的问题是:有没有更好的方法来做到这一点? The code works but该代码有效,但

a.一种。 its smelly and它的臭和

b.If i want more than 2 overloads it gets uglier如果我想要超过 2 个重载,它会变得更丑

thanks!谢谢!

由于我有许多具有相同名称的可覆盖方法,因此我创建了一个小模式来跟踪使用了哪个覆盖(在 base.MyMethod() 中)。然后,用户可以调用任何重载,应用程序将循环遍历所有重载,直到它看到有人将其“已执行”标志设置为真。然后执行“真正的基本方法”并中断循环。我想这种模式可以描述为“具有模糊入口点的单个覆盖的链式重载”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM