![](/img/trans.png)
[英]Method overriding can have different number of parameters in subclass and parent class ?Can the no.of parameters differ?
[英]Can a subclass override a method and have different parameters?
我想在多個子類中都有一個方法,該方法本質上可以完成某件事(例如獲取用戶信息),但是在主類中聲明(並且具有與主類不同的參數和定義)。 這可能嗎?
我知道這並不是真正的壓倒一切,但是可以做到這一點嗎,或者這不是構造方法的合適方法嗎?
您要執行的操作稱為重載方法。 它是可行的,並且經常發生。 在這里玩小提琴。 Java是相似的。
public class Parent
{
public virtual string HelloWorld()
{
return "Hello world";
}
public string GoodbyeWorld()
{
return "Goodbye world";
}
}
public class Child : Parent
{
// override: exact same signature, parent method must be virtual
public override string HelloWorld()
{
return "Hello World from Child";
}
// overload: same name, different order of parameter types
public string GoodbyeWorld(string name)
{
return GoodbyeWorld() + " from " + name;
}
}
public class Program
{
public static void Main()
{
var parent = new Parent();
var child = new Child();
Console.WriteLine(parent.HelloWorld());
Console.WriteLine(child.HelloWorld());
Console.WriteLine(child.GoodbyeWorld());
Console.WriteLine(child.GoodbyeWorld("Shaun"));
}
}
您可以使用相同名稱的方法的多個版本,但使用不同數量的參數。 您可以在主/父類中擁有所有這些功能,也可以僅在子類中添加較新的版本。 這樣做沒有任何限制。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.