C# Override with different parameters?

痞子三分冷 提交于 2019-12-10 13:26:28

问题


Here is an example of what I am looking to do.

public class A
{
    public virtual void DoSomething(string a)
    {
      // perform something
    }
}
public class B : A
{
    public Override void DoSomething(string a, string b)
    {
      // perform something slightly different using both strings
    }
}

So I want to override DoSomething from class A and allow it to pass a second parameter. Is this possible?


回答1:


When overriding a virtual method, you must keep the original "contract" of the method, which in your case is a string a variable.

In order to do what you want, you can create a virtual overload which takes two strings:

public class A
{
    public virtual void DoSomething(string a)
    {
      // perform something
    }
    public virtual void DoSomething(string a, string b)
    {
      // perform something
    }
}

public class B : A
{
    public override void DoSomething(string a, string b)
    {
      // perform something slightly different using both strings
    }
}

If what you want is to accept N strings in your method, you can use the params keyword:

public class A
{
    public virtual void DoSomething(params string[] allStrings)
    {
      // Do something with the first string in the array
      // perform something
    }
}



回答2:


No, this won't work. When overriding the methods needs to have the same prototype.




回答3:


No, this would be overloading. Since the logic would be 'slightly different' it sounds like you would need two different methods anyway? You could put your similar logic in a 3rd method and call that from both DoSomething(string A) and DoSomething(string A, string B)




回答4:


Slight necro, but when you overload you can call the original method from the new one.

so

public class B : A {

    public virtual void DoSomething (string a, string b) {
        base.DoSomething(_a);
        //Do B things here
    }
}

This allows you to modify the method instead of completely redoing it :)



来源:https://stackoverflow.com/questions/27547122/c-sharp-override-with-different-parameters

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!