简体   繁体   English

使用反射获取实际的返回类型表单Task <List<Dictionary<string,object> &gt;&gt;代替对象

[英]Use reflection to get actual return type form Task<List<Dictionary<string,object>>> instead of object

I am trying to get the actual object that is contained within a list that itself is contained within a task. 我试图获取包含在任务本身中包含的列表中的实际对象。

eg method has the following signature eg 方法具有以下签名,例如

public async Task<List<Dictionary<string,object>>> GetData()

i am currently using something like this: 我目前正在使用这样的东西:

var member = type.GetMembers()[0];
var returntype = member.ReturnType.GetGenericArguments();
var temp = member.ReturnType.GetGenericArguments()[0];
if (temp.GetGenericArguments().Count() > 0)
{
    temp.GetTypeInfo().GetGenericArguments();
    var innerttype = temp.GetGenericArguments()[0].FullName;
}

Currently the above code (which is not complete but just an extract from actual code) return system.object as fullname instead of Dictionary. 当前,以上代码(还不完整,仅是实际代码的一部分)返回system.object作为全名而不是Dictionary。

Any suggestions to solve this are welcome. 欢迎提供解决此问题的任何建议。

If you declare your dictionary to be of type <string, object> and and only ever insert objects inside it and not something higher up in the graph, you'll only ever get object typed objects out of it. 如果您将字典声明为<string, object>类型,并且只在其中插入对象,而不在图中插入更高的对象,则只会从中获得object类型的对象。

If you're storing all kinds of things in there and need to get their concrete type so you can interact with them, try to make them all conform to an interface first. 如果要在其中存储各种各样的东西,并且需要获取它们的具体类型以便可以与它们交互,请尝试首先使它们全部符合接口。 Then, put the interface type in there replacing "object." 然后,在其中放置接口类型以替换“对象”。 If that doesn't work you can use generics. 如果这样不起作用,则可以使用泛型。 However, you'll still need to know the type ahead of time in order to be able to interact with it. 但是,您仍然需要提前知道类型以便能够与它进行交互。

If you really have no idea what's in there and want to dig into it dynamically, that's precisely what Reflection was built for. 如果您真的不知道其中包含什么,并想动态地进行深入研究,那正是Reflection的目的。 You could also look into the dynamic type . 您也可以查看dynamic类型

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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