【问题标题】:How can I make a subroutine out of this C# code?如何使用此 C# 代码制作子例程?
【发布时间】:2016-08-03 01:27:54
【问题描述】:

我有以下 C# 代码,并且在我的代码中重复使用了大约 20 倍。我不知道如何将它变成一个允许我重复使用它的子例程,因为对象的类型每次都基于不同的类。

代码的目的是发送一个 HTTP 请求,收集 JSON 响应,然后将 JSON(使用 DataContract)序列化为一个类以用于其他领域。

这是我得到的:

    public static ResponseAttachmentIds MakeRequestAttachmentId(string requestUrl, string strToken)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            request.Headers["Authorization"] = "OAuth " + strToken;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(ResponseAttachmentIds));
                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                ResponseAttachmentIds jsonResponse = objResponse as ResponseAttachmentIds;
                response.Close();
                return jsonResponse;
            }
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show(e.Message);
            return null;
        }

    }

用于此特定用途的 DataContract 类是:

public class ResponseAttachmentIds
{
    [DataMember(Name = "done")]
    public bool attachmentIds_done;
    [DataMember(Name = "records")]
    public List<ResponseAttachmentId> attachmentIds_records;
}
[DataContract]
public class ResponseAttachmentId
{
    [DataMember(Name = "Id")]
    public string attachmentId_strId { get; set; }
    [DataMember(Name = "Image_Attachment_Id__c")]
    public string attachmentId_strAttachmentId { get; set; }
}

问题是我也为大约 20 个不同的类设置了相同的设置,例如 ResponseImagesResponsePropertiesResponseProperty 等。

有什么帮助吗?

【问题讨论】:

  • 除了托尼和保罗的回答,我建议DataContractJsonSerializer 非常有限。你可能想看看 NewtonSoft 的 Json 序列化器(你可以在 Nuget 上找到它)

标签: c# json rest datacontractserializer


【解决方案1】:

我相信您想要的是这样的通用方法:

public static T MakeRequestAttachmentId<T>(string requestUrl, string strToken) where T : class
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            request.Headers["Authorization"] = "OAuth " + strToken;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                var jsonResponse = (T)objResponse;
                response.Close();
                return jsonResponse;
            }
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show(e.Message);
            return default(T);
        }

    }

你可以这样称呼它:

MakeRequestAttachmentId<ResponseAttachmentIds>("", "");

【讨论】:

    【解决方案2】:

    我会更改方法以使用泛型。比如……

    public static T MakeResponseObject<T>(string requestUrl, string strToken)
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
            request.Headers["Authorization"] = "OAuth " + strToken;
            using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
            {
                if (response.StatusCode != HttpStatusCode.OK)
                    throw new Exception(String.Format(
                    "Server error (HTTP {0}: {1}).",
                    response.StatusCode,
                    response.StatusDescription));
                DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(T));
                object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
                var jsonResponse = objResponse as T;
                response.Close();
                return jsonResponse;
            }
        }
        catch (Exception e)
        {
            System.Windows.Forms.MessageBox.Show(e.Message);
            return null;
        }
    }
    

    【讨论】:

    • 感谢您的回复,您几乎在同一时间给出了与其他用户几乎相同的回复。我把答案给了另一个 b/c 我认为以 DataContractJsonSerializer 开头的行中有一个错误,而另一个用户给了我用法。
    • @gotmike 不用担心。在其他新闻中,我会小心地将响应 JSON 转换为泛型类型 T 以防对象在没有更新源的情况下发生更改。这就是我改用“as”关键字的原因。细微差别,但可能会对您的代码处理更新的能力产生重大影响。
    猜你喜欢
    • 2015-08-19
    • 2022-01-19
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    • 2022-06-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多