[英]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.以下是用于与 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
:并不完全清楚你的意思,但你试图投射的对象只是
System.Object
一个实例:
(T)new object()
That can never work unless T
itself is object
.除非
T
本身是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
).这里的问题似乎是您正在尝试使用一种专为处理匿名类型而设计的方法(因此第二个参数作为“示例”出现以使类型推断工作) - 但类型不是匿名的(
T
)。
I suspect you just want:我怀疑你只是想要:
return JsonConvert.DeserializeObject<T>(restResponse.Content);
In your method last line (T)new object()
is a problem.在你的方法最后一行
(T)new object()
是一个问题。 This makes no sense.这没有任何意义。 You're creating new instance of
System.Object
and trying to cast it to T
where T
could be anything.您正在创建
System.Object
新实例并尝试将其System.Object
转换为T
,其中T
可以是任何内容。 Your method is going to succeed only when called with generic parameter T
as System.Object
.只有在使用泛型参数
T
作为System.Object
调用时,您的方法才会成功。 For example GetRequest<object>(...)
will pass, otherwise it will fail.例如
GetRequest<object>(...)
会通过,否则会失败。
Am not sure what you're trying to achieve here.不知道你想在这里实现什么。 If you can provide more info it will be easy to help.
如果您能提供更多信息,将很容易提供帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.