错误CS0120:非静态字段,方法或属性需要对象引用

时间:2019-05-23 18:35:56

标签: c#

我在下一行中收到此错误消息,但我不知道自己在做什么错。

 Scorelist.Add(entry.StatValue);
  

错误CS0120:非静态需要对象引用   字段,方法或属性“ Game1.Scorelist”

如何解决此问题?

  public List<int> Scorelist = new List<int>();

  NewClient();

  public async void NewClient()
  {
      await DoReadLeaderboard();
  }

    private static async Task DoReadLeaderboard()
    {
        // Get Leaderboard Request
        var result = await PlayFabClientAPI.GetLeaderboardAsync(new GetLeaderboardRequest()
        {
            // Specify your statistic name here
            StatisticName = "TestScore",
            // Override Player Profile View Constraints and fetch player DisplayName and AvatarUrl
            ProfileConstraints = new PlayerProfileViewConstraints()
            {
                ShowDisplayName = true,
                ShowAvatarUrl = true
            }
        });


        if (result.Error != null)
        {
            // Handle error if any
            Console.WriteLine(result.Error.GenerateErrorReport());
        }
        else
        {
            // Traverse the leaderboard list
            foreach (var entry in result.Result.Leaderboard)
            {                  
                Scorelist.Add(entry.StatValue);
            }
        }
    }

1 个答案:

答案 0 :(得分:0)

您正在使用属性Scorelist,但这不是静态属性,并且您没有该类的实例。您可能会认为,因为从成员方法中调用它是可以的,但是由于此方法是静态的,所以不是。您有3种解决方案:

1)将DoReadLeaderboard()设为非静态:

private async Task DoReadLeaderboard()

2)将Scorelist设为静态:

public static List<int> Scorelist = new List<int>();

3)创建该类的实例,并访问它的Scorelist

var instance = new <<ClassName>>();
instance.Scorelist.Add(entry.StatValue);