如何使用ref?

Dim*_*zyr 2 c# ref

我正在学习使用ref,但无法理解,为什么我收到错误?

class A
{
    public void ret(ref int variable)
    {
        variable = 7;
    }

    static int Main()
    {
        int z = 5;
        ret(ref z); // Error: Need a reference on object
        Console.WriteLine(z); // it will be 7 as I understand
        return 0;
    }
}
Run Code Online (Sandbox Code Playgroud)

p.s*_*w.g 9

问题不在于ref参数.这ret是一个实例方法,如果没有对该类型实例的引用,则无法调用实例方法.

尝试制作ret静态:

public static void ret(ref int variable)
{
    variable = 7;
}
Run Code Online (Sandbox Code Playgroud)


Typ*_*eIA 5

ref正确使用.该错误实际上是因为ret()是一个实例方法,Main()而是静态的.make ret()static也是如此,这段代码将按照您的预期编译和工作.