class Program
{
static void Main(string[] args)
{
double weight;
string num;
num = getWeight(out weight);
Console.WriteLine(num + " lb = " + lbToKg(weight) + "kg");
kgToLb(ref weight);
Console.WriteLine(num + " kg = " + weight + "lb");
}
static string getWeight (out double theWeight)
{
theWeight = 10;
return "Ten";
}
static double lbToKg(double pounds = 2)
{
return (pounds * 0.45359237);
}
static void kgToLb (ref double weight)
{
weight = (weight / 0.45359237);
}
}
所以我想我的问题是,在什么时候“theWeight”变成了“weight”,是什么允许这种情况发生的?它是getWeight()方法中列出的输出(out)吗?如果是这样的话,是怎么做的?ref参数对此有何影响?
我觉得我离实现它已经很近了,我只是想弄清楚它到底是如何工作的,为什么会这样。
发布于 2018-10-14 21:47:07
在这种情况下,ref
和out
几乎是一样的。不同之处在于,使用ref
时,对象必须在进入函数之前初始化,而使用out
时,对象将在函数内部初始化。因为您的对象是double
,所以不需要初始化,这两个关键字的工作方式完全相同。唯一的区别是,使用out
时,必须赋值,而使用ref
时,这是可选的。
static void Main(string[] args)
{
double weight;
string num;
num = getWeight(out weight);
// here weight goes to the function and comes back with value of 10.
Console.WriteLine(num + " lb = " + lbToKg(weight) + "kg");
kgToLb(ref weight);
// here again weight goes to the function and comes back with a new value
Console.WriteLine(num + " kg = " + weight + "lb");
}
因此,实际上theWeight
是一个局部变量,它在函数getWeight
中保存weight
的引用。kgToLb
函数中的权重也是一样的。希望这一点是清楚的。
您可以在这里阅读更多内容https://www.dotnettricks.com/learn/csharp/difference-between-ref-and-out-parameters
https://stackoverflow.com/questions/52806769
复制相似问题