学习 C# ref 和 out 如何允许它在这个特定实例中工作?

Learning C# How does ref and out allow this to work in this specific instance?

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 参数如何影响这个?

我觉得我已经很接近这个了,我只是想完全清楚它是如何工作的以及为什么会这样。

他们似乎在做同样的事情,但实际上发生的事情有很大的不同。这两者都是通过引用传递参数,但它们的用例不同,规则也不同。

'theWeight' become 'weight'

因为在这两种情况下都是通过引用传递的,所以 theWeightweight 都引用相同的值。

当您使用ref命令时,您传入的变量必须在调用之前进行初始化。使用 out.

时不必如此

但另一方面,在方法中使用out时,必须在方法完成之前将其标记的参数赋值。

还有一些不同之处,但要指出的要点是两者都是通过引用传递变量。

refout 在这种情况下几乎是一样的。不同之处在于,使用 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