简体   繁体   中英

Generic Method Unable to cast object of type 'System.Object' to type X

I am new to creating generic methods and have come across casting issues.

The following is a class library for communicating with an API. The object I am trying to cast to lives in my main application, which might be the issue but I do not know. What might I be doing wrong?

public T GetRequest<T>(Authentication auth, string api)
{
     var restClient = new RestClient(Constants.Api.Client);

     var restRequest = new RestRequest(api, Method.GET);
     SetParameters(restRequest, auth);

     var restResponse = restClient.Execute(restRequest);

     return JsonConvert.DeserializeAnonymousType<T>(restResponse.Content, (T)new object());
}

The object I am trying to cast to lives in my main application

It's not entirely clear what you mean by that, but the object you're trying to cast is just an instance of System.Object :

(T)new object()

That can never work unless T itself is object .

The problem here appears to be that you're trying to use a method designed for working with anonymous types (so the second parameter is present as an "example" to make type inference work) - but with a type which isn't anonymous ( T ).

I suspect you just want:

return JsonConvert.DeserializeObject<T>(restResponse.Content);

In your method last line (T)new object() is a problem. This makes no sense. You're creating new instance of System.Object and trying to cast it to T where T could be anything. Your method is going to succeed only when called with generic parameter T as System.Object . For example GetRequest<object>(...) will pass, otherwise it will fail.

Am not sure what you're trying to achieve here. If you can provide more info it will be easy to help.

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