我正在使用 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/