C# Cannot Call Static Method Through Instance

Asked 1 years ago, Updated 1 years ago, 101 views

class playerstatus{
    public static int coin=100;
}

US>class sample {
    cointext.text="coins:"+playerstatus.coin.ToString();
}

This brings up cs0176 and Static member'playerstatus.coin'cannot be accessed with an instance reference, validate it with a type name installed

This seems to be a specification, but is there any other way?

c# unity3d

2022-09-30 21:09

1 Answers

The cointext.text="coins:"+playerstatus.coin.ToString(); part is not contextually written (cannot be written as a local sentence in the class), so the code does not reproduce the question.
The following code can be executed as expected, so I don't think it's the same as the actual code (I didn't call it from the instance).

using System;

class playerstatus {
    public static int coin=100;
}

class sample
{
    static void Main (string[]args)
    {
        string text="coins:"+playerstatus.coin.ToString();//Converts with string and does not require ToString()
        Console.WriteLine(text);
        /* Perhaps the questioner's situation is doing this.
        playerstatus p = new playerstatus();
        Console.WriteLine(p.coin);//coin cannot be done because it is not a member of the instance.Static members are called from the class name (as shown in the error message).
        */
    }
}


2022-09-30 21:09

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.