我有以下代碼:方法與價值和參考的參數類型重載
class Calculator
{
public int Sum(int x, int y)
{
return x + y;
}
public int Sum(out int x, out int y)
{
x = y = 10;
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
Calculator calculator = new Calculator();
Console.WriteLine (calculator.Sum (x , y));
Console.WriteLine (calculator.Sum (out x , out y));
}
}
此代碼工作做好儘管方法簽名只differenciated是out
關鍵字。
但下面的代碼沒有工作:
class Calculator
{
public int Sum(ref int x, ref int y)
{
return x + y;
}
public int Sum(out int x, out int y)
{
x = y = 10;
return x + y;
}
}
class Program
{
static void Main(string[] args)
{
int x = 10, y = 20;
Calculator calculator = new Calculator();
Console.WriteLine (calculator.Sum (ref x , ref y));
Console.WriteLine (calculator.Sum (out x , out y));
}
}
爲什麼這個代碼不工作? 關鍵字像ref和out方法簽名的一部分嗎?
'ref'和'out'編譯幾乎同樣的事情,所以C#不允許你這樣做。 –