C# 方法 returns int-by value or reference

C# method returns int-by value or reference

我正在尝试计算方法返回的 int 的存储位置。我假设它是堆栈,但想澄清一下。场景如下:

public int returnInt()
{
   var returnVal=1:
   Return returnVal;
}

在这种情况下,我知道 returnVal 将存储在堆栈中,并在 returnInt 方法具有 运行 时弹出。实际上,returnVal 是一个值类型,因此不会通过引用传递。

我不清楚的部分如下:

public void callerMethod()
{
    var intVal=returnInt();
}

我认为这里发生的是实际值被返回,并保存在堆栈上的新内存位置,供 callerMethod 使用。

谁能证实这是否正确?还请随时纠正我所说的其他任何不正确的地方...

callerMethod()中的值是一个新值,独立于returnInt()中的值。

希望下面的示例对您有所帮助。

static int myStaticInt = 333;
public static int returnInt()
{
    return myStaticInt;
}

public static void callerMethod()
{
    var i = returnInt();
    i += 100;
    Console.WriteLine(i);
}

public async static Task Main(string[] args)
{
    Console.WriteLine(myStaticInt);
    callerMethod();
    Console.WriteLine(myStaticInt);
}

输出

333
433
333

结果

myStaticInt 仍然是 333.


这是来自 Passing Value-Type Parameters (C# Programming Guide) 的相关部分:

A value-type variable contains its data directly as opposed to a reference-type variable, which contains a reference to its data. Passing a value-type variable to a method by value means passing a copy of the variable to the method. Any changes to the parameter that take place inside the method have no affect on the original data stored in the argument variable.

这里有一些关于 C# 规范 Types 部分的赋值。

Assignment to a variable of a value type creates a copy of the value being assigned. This differs from assignment to a variable of a reference type, which copies the reference but not the object identified by the reference.


通过引用传递和 returning 值类型

请注意,可以通过引用传递和 return 值类型。

请参阅 Passing Value-Type Parameters (C# Programming Guide) and Ref returns and ref locals 通过引用传递值类型 部分。

有了这些知识,现在让我们修改示例并检查结果。

static int myStaticInt = 333;
public static ref int returnInt()
{
    //var returnVal = 1;
    return ref myStaticInt;
}

public static void callerMethod()
{
    ref var i = ref returnInt();
    i += 100;
    Console.WriteLine(i);
}

public async static Task Main(string[] args)
{
    Console.WriteLine(myStaticInt);
    callerMethod();
    Console.WriteLine(myStaticInt);
}

输出

333
433
433

结果

myStaticInt现在是433,不是原来的333