2013-01-23 55 views
2

如何在本示例中使用重載方法。當我發送增量時,它應該給我新的價值。如果我不給增量,它應該添加一個默認值。這是在c#asp.net中。以示例超載的概念

例如:

GetY(y,3) // add 3 to y 

or GetY(y) //add default value of 15 

謝謝!

回答

3

您可以使用可選參數來指定默認值,然後重載不是必需的。

public int GetY(int y, int add = 15) { 
    return y + add; 
} 

這是一樣的以下重載版本:

public int GetY(int y) { 
    return GetY(y, 15); 
} 

public int GetY(int y, int add) { 
    return y + add; 
} 
2
public int GetY(int y, int increment) 
{ 
    return y + increment; 
} 

public int GetY(int y) 
{ 
    return GetY(y, 15); 
} 
+2

你的方法參數需要的數據類型。 – mellamokb

+0

+1哦!是。我糾正它。謝謝 –