c# - 学习 C# ref 和 out 如何允许它在这个特定实例中工作?
问题描述
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”在什么时候变成“重量”,是什么让这种情况发生?它是 getWeight() 方法中列出的输出(输出)吗?如果是这样怎么办?以及 ref 参数如何影响这一点?
我觉得我离这个很近了,我只是想完全清楚它是如何以及为什么起作用的。
解决方案
ref
并且out
在这种情况下几乎相同。不同之处在于withref
对象在进入函数之前必须进行初始化,而without
对象会在函数内部进行初始化。由于您的对象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
是一个局部变量,它包含weight
函数内部的引用getWeight
。函数内部的权重也是如此kgToLb
。希望这很清楚。
你可以在这里阅读更多 https://www.dotnettricks.com/learn/csharp/difference-between-ref-and-out-parameters
推荐阅读
- python - 如何使用烧瓶在文件中的表中显示输出
- python - 我正在为单词益智游戏编写代码,但不知道如何将文本行包含到循环中
- python - 使用代理连接到 Google Cloud SQL 的 SQLAlchemy 错误
- sql - 如何在 DB2 中验证日期
- javascript - 是否有 Julia 的 JavaScript 和 TypeScript 元编程和宏的等价物?
- kotlin - Are Kotlin suspend functions blocking?
- css - 如何在引导程序中给按钮一个按钮右对齐?
- python - 从 Jupyter 笔记本文件夹中打开多个泡菜文件不起作用
- java - 复制和更改 zip 存档
- java - 返回布尔语句列表的惰性求值,其中任何一个为真