如何将IDictionary <object,string>转换为Unity中的ParseObject?

时间:2016-01-20 07:45:33

标签: c# parse-platform unity3d casting cloud

我已经定义了一个名为LeaderboardScore的ParseObject子类,它从我的云代码函数返回为IDictionary<string, object>

我希望我可以像下面的例子中那样做,但演员表失败了:(

投射失败的尝试:

ParseCloud.CallFunctionAsync<IDictionary<string, object>>("getScore", parameters).ContinueWith(t =>
{
    LeaderboardScore score = t.result as LeaderboardScore;
    Debug.Log(score.get<string>("facebookId"));
}

LeaderboardScore定义:

[ParseClassName("LeaderboardScore")]
public class LeaderboardScore : ParseObject
{
    [ParseFieldName("facebookId")]
    public string FacebookId
    {
        get { return GetProperty<string>("FacebookId"); }
        set { SetProperty<string>(value, "FacebookId"); }
    }

    [ParseFieldName("score")]
    public int Score
    {
        get { return GetProperty<int>("Score"); }
        set { SetProperty<int>(value, "Score"); }
    }
}

请注意,t.Result确实有正确的信息,这意味着我可以通过调用t.Result["facebookId"] as string之类的东西来访问它,但是能够传递LeaderboardScore对象而不是{{1}会更好。 }}

如果有人能对这个问题有所了解,我将不胜感激! :)

2 个答案:

答案 0 :(得分:1)

您可以通过以下方式将所有字典强制转换为对象(带属性):

public static T ToObject<T>(this IDictionary<string, object> source)
    where T : class, new()
{
    T someObject = new T();
    Type someObjectType = someObject.GetType();

    foreach (KeyValuePair<string, object> item in source)
    {
        someObjectType.GetProperty(item.Key).SetValue(someObject, item.Value, null);
    }

    return someObject;
}

答案 1 :(得分:0)

执行此操作的正确方法是为您感兴趣的每个ParseObject创建native subclasses,然后让您的云函数返回该类型或该类型的列表,如下所示:

ParseCloud.CallFunctionAsync<LeaderboardScore>("getScore", parameters).ContinueWith(t =>
{
    LeaderboardScore score = t.Result;
}

Parse负责转换,因此您不必担心。要返回列表,只需使用IList<LeaderboardScore>

即可