将变量类型传递给构造函数,并返回传入的相同类型

时间:2016-04-18 03:23:39

标签: c# object methods constructor

我需要将变量对象类型作为参数传递给构造函数,并且能够从它构造的方法返回变量类型。很难解释所以代码可能会做得更好。

将对象类型传递给构造函数,我试过了。

public async Task<BlockData.Block> Last()
{
    return await new AsyncConnector<BlockData.Block>(Connection).Get(
        "/chain/last-block"
        );
}

并接收它,我这样做:

public class AsyncConnector<T>
{
    NisConnection Connection = null;

    public AsyncConnector(NisConnection connection)
    {
        Connection = connection;
    }

    public async Task<T> Get(string uri)
    {
        var response = await Connection.Client.GetAsync(Connection.FullUri(uri));

        return JsonConvert.DeserializeObject<T>(
            JObject.Parse(await response.Content.ReadAsStringAsync()).ToString()
        );
    }
}

我也试过这个:

public async Task<BlockData.Block> Last()
{
    return await new AsyncConnector(Connection).Get<BlockData.Block>(
        "/chain/last-block"
        );
}

public class AsyncConnector
{
    NisConnection Connection = null;

    public AsyncConnector(NisConnection connection)
    {
        Connection = connection;
    }

    public async Task<T> Get<T>(string uri)
    {
        var response = await Connection.Client.GetAsync(Connection.FullUri(uri));

        return JsonConvert.DeserializeObject<T>(
            JObject.Parse(await response.Content.ReadAsStringAsync()).ToString()
        );
    }
}

GetAsync方法需要以相同的方式工作,但对于许多不同的对象类型。

我不断得到的错误是:

  

类型&#39; Microsoft.CSharp.RuntimeBinder.RuntimeBinderException&#39;的例外情况发生在mscorlib.dll但未在用户代码中处理
  附加信息:无法转换类型&#39; Newtonsoft.Json.Linq.JObject&#39;到了NemApi.DTOs.BlockObjects.BlockData.Block&#39;

1 个答案:

答案 0 :(得分:0)

如果您只是使用System.Net.Http.Formatting中的ReadAsAsync<T>,它会将您的JSON转换为引擎盖下的强类型对象。您无需在其上进行转换或解析。

public async Task<BlockData.Block> Last()
{
    return await new AsyncConnector(Connection).Get<BlockData.Block>(
        "/chain/last-block");
}

public class AsyncConnector
{
    NisConnection Connection = null;

    public AsyncConnector(NisConnection connection)
    {
        Connection = connection;
    }

    public async Task<T> Get<T>(string uri)
    {
        var response = await Connection.Client.GetAsync(Connection.FullUri(uri));
        return await response.Content.ReadAsAsync<T>();
    }
}