c# - 从一个 Action 中调用一个 Action

标签 c# unity3d gree

我正在使用 GREE c# API 在 Unity3d 中创建游戏。 我正在尝试为排行榜中的每个(用户名、分数)运行一个Action

代码如下:

public static void LoadBestScoreFromFriends(Action<FriendAndScore> onComplete)
{
    Gree.Leaderboard.LoadScores(LEADERBOARD_ID,
        UnityEngine.SocialPlatforms.UserScope.FriendsOnly,
        UnityEngine.SocialPlatforms.TimeScope.AllTime,
        1,
        100,
        (IScore[] scores) => {

        foreach (IScore iscore in scores)
        {
            // Since the username is needed, a second
            // call to the API must be done
            Gree.User.LoadUser(iscore.userID, 
            (Gree.User guser) => {
                FriendAndScore friend = new FriendAndScore();
                friend.Name = guser.nickname;
                friend.Score = "" + iscore.value;

                // Run the action for every (nickname, score value)
                onComplete(friend);
            }, (string error) => {
                Debug.Log("Couldn't fetch friend! error: " + error);
            });
        }
    });
}

这里的问题是 iscore.value 它总是相同的。它是 foreach 的最后一个元素。这是有道理的,因为 LoadUser()foreach 结束其循环之后完成。

我想创建第二种方法来在那里进行调用。像这样的东西:

private void GetTheUserAndCallTheAction(Action<FriendAndScore> onComplete, string userID, string score)
{
    Gree.User.LoadUser(userID, 
            (Gree.User guser) => {
                FriendAndScore friend = new FriendAndScore();
                friend.Name = guser.nickname;
                friend.Score = score;
                onComplete(friend);
            }, (string error) => {
                Debug.Log("Couldn't fetch friend! error: " + error);
            });
}

因为我是一个 C# 新手,所以我想知道是否有更好的方法来处理这个问题。

最佳答案

按照设计 - 这就是在 foreach 循环中构造 lambda 表达式并稍后执行此 lambda 时捕获的工作方式。

修复 - 声明 IScore iscore 的本地副本:

foreach (IScore eachScore in scores)
{
   IScore iscore = eachScore;

Closing over the loop variable... Eric Lippert 详细介绍了行为和相关问题。

关于c# - 从一个 Action 中调用一个 Action ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13241452/

相关文章:

c# - 激活 IInterceptor 时出错...仅通过 COM?

c# - 通过 Unity 中的脚本更改作为 2D Sprite 子项的 TextMeshPro 文本

git - 为什么忽略的文件没有被忽略?

android - Unity3D Build Configuration 省略 iOS 包

c# - 仅仅为了提供默认状态/配置而进行子类化是否可以?

c# - 无法安装 msi 包,要求 .Net framework 4

C#线程声明

c# - UnityWebRequest如何打印所有Request headers

c# - 有没有像 c# 的 python 装饰器之类的东西?