返回通用对象类型

时间:2016-09-13 12:07:04

标签: c# generics .net-3.5

我们GitHub Gist的完整代码我只包括我认为需要显示问题的部分。

执行方法:

  public object Execute()
        {
            var request = createWebRequest();
            request.Method = this.Method;
            applyPostData(ref request);

            request.ContentType = "application/json";
            request.UserAgent = "generic-http-dotnet-client/3.5/v1 (gzip)";

            var response = (HttpWebResponse)request.GetResponse();

            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

            try
            {
                return JsonConvert.DeserializeObject(responseString);
            }
            catch (Exception)
            {
                return new HttpResponse { message = responseString };
            }
        }

好的,这种方式很有用。然而,我希望能够做的是在调用该方法之后将其转换为适当的对象类型。

var response = (MetaDataResponse)request.Execute();

我知道应该有一些方法可能使用泛型(Wild guess)让我对json DeserializeObject的响应并返回它?

我最终将execute方法的返回类型更改为字符串,并执行此操作。

public class MetaDataRequest : HttpRequestBase
    {
        public MetaDataResponse MetaDataItems { get; private set; }

        public MetaDataRequest() : base(new Uri("https://www.googleapis.com/analytics/v3/metadata/ga/columns"), "GET")
        {
            this.addParameter("key", "xxxx");
            var response = this.Execute();

            try
            {
                MetaDataItems =  JsonConvert.DeserializeObject<MetaDataResponse>(response);
            }
            catch (Exception)
            {
                var resultsx = new HttpResponse { message = response };
            }
        }
    }

哪个有效,但接缝对我来说很乱。请注意,此项目是 .Net framework 3.5 ,我无法改变它。随意添加您能想到的任何其他标签。

2 个答案:

答案 0 :(得分:1)

对类MetaDataRequest使用泛型

class MetadataRequest<T>:HttpRequestBase
{
    public T Execute()
    {
        var request = createWebRequest();
        request.Method = this.Method;
        applyPostData(ref request);

        request.ContentType = "application/json";
        request.UserAgent = "generic-http-dotnet-client/3.5/v1 (gzip)";

        var response = (HttpWebResponse)request.GetResponse();

        var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();

        return JsonConvert.DeserializeObject<T>(responseString);
    }
}

然后,要获取对象,可以像这样调用方法:

MetadataResponse responseObject = (new MetadataRequest<MetadataResponse>()).Execute();

在这种情况下,您可以捕获.Execute()抛出的异常,因为它只能返回null或类型为T的实例。

编辑:您也可以按照Jeremy Holovacs' answer使用通用方法。

答案 1 :(得分:1)

首先,要点是没有处理它的IDisposables,这非常草率。我推荐这样的东西:

public T Execute<T>()
    {
        var request = createWebRequest();
        request.Method = this.Method;
        applyPostData(ref request);

        request.ContentType = "application/json";
        request.UserAgent = "generic-http-dotnet-client/3.5/v1 (gzip)";

        using(var response = (HttpWebResponse)request.GetResponse())
        using(var stream = response.GetResponseStream())
        using(var reader = new StreamReader(stream))
        {
            try
            {
                var responseString = reader.ReadToEnd();
                return JsonConvert.DeserializeObject<T>(responseString);
            }
            catch (Exception ex)
            {
                //log something with ex
                return default(T);
            }
        }
    }