c# - c# 编译器是否在编译期间解析引用的引用?

标签 c# pointers reference

据我所知,在 C 编程语言中,如果将任何指针分配给另一个指针,我们将使用 ** 前缀来访问原始值。

当我将对象实例作为 ref Myobject myObject 参数传递给方法时,这是如何工作的。 c#是否解析对象的堆地址并在下面的代码中调用printSomething

void testFunction(ref MyObject myObject){
    myObject.printSomething();
}

那么如果这是一个递归函数,编译器会跟随引用地址直到找到对象吗?

我在下面添加一个测试场景;

public class Test
{


    public Test()
    {
        StringBuilder str = new StringBuilder();
        Function(ref str);
        Console.WriteLine(str.ToString());
    }

    int referenceCount = 0;

    int Function(ref StringBuilder sBuilder)
    {
        referenceCount++;

        if (referenceCount == 100)
        {
            sBuilder.Append("foo");
            return referenceCount;
        }

        Function(ref sBuilder);
        return referenceCount;
    }

    public static void Main(string[] args)
    {
        new Test();
        Console.ReadLine();
    }

}

如果我删除 if block ,如预期的那样给出堆栈溢出异常,那么对于每个方法调用,在堆栈中保留一个新引用。在将它们中的 100 个相互链接之后,我在最后一个上调用一个方法。 sBuilder.Append("foo"); 代码会跟随链接引用直到到达对象吗?

最佳答案

看看这个article .

C# 中的 Ref 不是 C++ 中的指针。这是不同的概念。

When used in a method's parameter list, the ref keyword indicates that an argument is passed by reference, not by value. The effect of passing by reference is that any change to the argument in the called method is reflected in the calling method. For example, if the caller passes a local variable expression or an array element access expression, and the called method replaces the object to which the ref parameter refers, then the caller’s local variable or the array element now refers to the new object when the method returns.

关于c# - c# 编译器是否在编译期间解析引用的引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47939851/

相关文章:

c# - HttpClient : Correct order to detect encoding

c - C中的指针问题

c++ - 什么是指向 x 个整数数组的指针?

C++ - 自动返回引用和非引用类型

c# - Object.Equals(obj, null) 和 obj == null 有什么区别

C#.NET 使用 block

c# - Combobox Itemsource 在设置为单个项目集合时抛出异常

c# - .Net 4 : How to reference a dynamic object with property named "return"

pointers - 使用变量地址调用指针接收器方法

C++:在成员函数中通过引用返回成员变量