简体   繁体   English

接口中的通用方法

[英]Generic methods in interface

I have an interface which basically does POST requests 我有一个基本上可以执行POST请求的接口

public interface IRestService
    {
        T Post<T>(string path, string payLoad) where T : class;
        string Post(string path, string payLoad);
    }

Is there a way, i can combine these two Post methods into one. 有没有办法,我可以将这两种Post方法合并为一个。 The first Post will deserailize the response string into a class The second Post is just to return the response as a string. 第一个Post会将响应字符串反序列化为一个类。第二个Post只是将响应作为字符串返回。

This is a common problem and it can be overcome by encapsulating the returned value in another class. 这是一个常见问题,可以通过将返回值封装在另一个类中来解决。 I am guessing the second one string Post is to return an error message. 我猜第二个string Post是要返回错误消息。 If that's the case you can do something like this: 如果是这种情况,您可以执行以下操作:

public class Response<T> where T : class {
    T data;
    string message;
    int statusCode //another field that would make error checking easier
}

public interface IRestService
{
    Response<T> Post<T>(string path, string payLoad) where T : class;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM