質問

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