简体   繁体   中英

Generic methods in interface

I have an interface which basically does POST requests

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. The first Post will deserailize the response string into a class The second Post is just to return the response as a string.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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