我有以下代码:
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 ) );
}
}
尽管方法签名仅在以下情况下有所区别,但该代码运行良好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 这样的关键字是方法签名的一部分吗?
out 参数修饰符(C# 参考) http://msdn.microsoft.com/en-us/library/ee332485.aspx
尽管 ref 和 out 关键字会导致不同的运行时行为,它们在编译时不被视为方法签名的一部分。因此,如果唯一的区别是方法不能重载
一个方法采用 ref 参数,另一种方法采用 out
争论。
另请参阅:ref(C# 参考 http://msdn.microsoft.com/en-us/library/vstudio/14akc2c7%28v=vs.120%29.aspx)
班级成员不能有仅 ref 和 不同的签名
出去。如果两者之间唯一的区别,则会发生编译器错误
类型的成员之一是其中一个具有 ref 参数,并且
other 有一个 out 参数。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)