创建接受类型对象的通用方法并返回类型为

时间:2015-11-22 10:09:47

标签: c# .net generics

我想使用RestSharp为我的服务请求和响应创建一个通用方法。 我想传递任何类的资源URL和对象名称,并希望得到我传递的相同对象类型的响应。

我找不到运行此代码的方法,我知道它不是完美的方式,但如果有人指示我正确的路径,我会很高兴 e.g。

class Employee
{
    Employee em = new Employee();
    RequestClass CreateRequest = new Request();
    public Employee GetAllEmployee()
    {
        return RequestClass.MyRequest("http://get-all-employee",em);
    }
}

class RequestClass
{
    public Type MyRequest(string resource, Type objectName)
    {
        var client = new RestClient("http://Service-url.com");
        var request = new RestRequest(resource, Method.GET);
        var response = client.Execute(request);
        var result = response.Content;

        Type ClassName = objectName.GetType();
        Object myobject = Activator.CreateInstance(ClassName);

        JsonDeserializer jsonDeserializer = new JsonDeserializer();
        myobject = jsonDeserializer.Deserialize<Type ClassName>(response);

        return (Type)myobject;
    }
}       

1 个答案:

答案 0 :(得分:5)

generic type parameter使用new() constraint

public T MyRequest<T>(string resource) where T : new()
{
    var client = new RestClient("http://Service-url.com");
    var request = new RestRequest(resource, Method.GET);
    var response = client.Execute(request);

    JsonDeserializer jsonDeserializer = new JsonDeserializer();
    return jsonDeserializer.Deserialize<T>(response);
}

然后像这样使用它:

public Employee GetAllEmployee()
{
    var requestClass = new RequestClass();
    return requestClass.MyRequest<Employee>("http://get-all-employee");
}