c# - 使用通用类型的开关序列化响应

标签 c# generics unity3d litjson

我在 Unity3D 项目上使用 LitJsonBestHTTP 库,我会编写自定义 ResponseSerializer 对象。 目标是创建一个使用泛型将可能的响应映射到我想要的对象的方法。

所以,我的第一次尝试是类似的:

public static void SerializeResponse<T>(string error, HTTPResponse response, string insideKey, Action<APIResource<T>> callback)
    where T:new()
{
    var apiResource = new APIResource<T>();

    if (error != null)
    {
        apiResource.error = error;
    }
    else
    {
        apiResource.error = null;
        JsonData jsonData = JsonMapper.ToObject(response.DataAsText);
        apiResource.resource = (T)(jsonData[insideKey]);
    }
    callback(apiResource);
}

但是这样我就得到了编译错误

apiResource.resource = (T)(jsonData[insideKey]);

留言:

Cannot convert type LitJson.JsonData to T

可能需要的 T 类型只有 4(目前):

  • 字符串
  • 内部
  • 漂浮
  • bool

所以,我开始玩 switch on 类型,但每次我都会遇到编译错误。我最后一次尝试是这样的(取自 https://stackoverflow.com/a/4478535/2838073 ):

public static void SerializeResponse<T>(string error, HTTPResponse response, string insideKey, Action<APIResource<T>> callback)
    where T:new()
{
    var apiResource = new APIResource<T>();

    if (error != null)
    {
        apiResource.error = error;
    }
    else
    {
        apiResource.error = null;
        JsonData jsonData = JsonMapper.ToObject(response.DataAsText);

        var @switch = new Dictionary<Type, Action> {
            { typeof(string),   () => { apiResource.resource = (string)jsonData[insideKey]; } },
            { typeof(int),      () => { apiResource.resource = (int)jsonData[insideKey]; } },
            { typeof(float),    () => { apiResource.resource = (float)jsonData[insideKey]; } },
            { typeof(bool),     () => { apiResource.resource = (bool)jsonData[insideKey]; }}
        };

        @switch[typeof(T)]();
    }
    callback(apiResource);
}

但是错误总是一样的:

Cannot implicitly convert type mytype to T

我做错了什么? 我不擅长使用泛型模式的 C#,我会从我的错误中吸取教训。

最佳答案

由于 T 包括值类型(例如 int)和引用类型(string),您需要 box转换为 object 之前从 jsonData[insideKey] 返回的值:

apiResource.resource = (T)(object)(jsonData[insideKey]);

关于c# - 使用通用类型的开关序列化响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46523525/

相关文章:

c# - Datatable 中的记录总数限制是多少?

c# - WP8 游戏开发和 C#

c# - C++/CLI 中使用的动态 C# 对象

c# - 使用 LINQ 查询自动检查 NULL 关系

java - 这个 Java 泛型范例是做什么的,它叫什么?

generics - Rust 中的泛型函数

android - Unity Oculus Android构建失败。启动守护程序

c# - 如何统一使用.Net 4.6.1?

c# - 如何获取表单上的所有标签并将具有特定名称模式的标签的 Text 属性设置为 string.empty?

android - 11.0.4 以上版本的 Google Play 服务下载