首页 > 解决方案 > 学习 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 参数如何影响这一点?

我觉得我离这个很近了,我只是想完全清楚它是如何以及为什么起作用的。

标签: c#methodsargumentsrefout

解决方案


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


推荐阅读