I'm learning to use ref, but can't understand, why I'm getting an error?

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;
    }
}
有帮助吗?

解决方案

The problem isn't with the ref parameter. It's that ret is an instance method, and you can't call an instance method without a reference to an instance of that type.

Try making ret static:

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

其他提示

You're using ref correctly. The error is actually because ret() is an instance method, while Main() is static. Make ret() static as well and this code will compile and work as you expect.

Your method is not static.You need to make is static like this:

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

Since ret is an instance method you can't access it without creating an object of the type.

Try making the method ret as static method like public static void ret(ref int variable)

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top