接口中的通用方法

时间:2019-01-31 22:27:26

标签: c# generics

我有一个基本上执行POST请求的接口

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

有没有办法,我可以将这两个Post方法组合为一个。 第一个Post将把响应字符串反序列化为一个类 第二个Post只是将响应作为字符串返回。

1 个答案:

答案 0 :(得分:1)

这是一个常见问题,可以通过将返回值封装在另一个类中来解决。我猜第二个string Post是要返回错误消息。如果是这种情况,您可以执行以下操作:

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;
}