如何在C#中获取动态对象的类型?

如何在C#中获取动态对象的类型?,c#,.net,list,dynamic,C#,.net,List,Dynamic,我有一个列表,我需要将列表的值和类型传递给服务。 服务代码如下所示: Type type = typeof(IList<>); // Type genericType = how to get type of list. Such as List<**string**>, List<**dynamic**>, List<**CustomClass**> // Then I convert data value of list to speci

我有一个
列表
,我需要将列表的值和类型传递给服务。 服务代码如下所示:

 Type type = typeof(IList<>);
 // Type genericType = how to get type of list. Such as List<**string**>, List<**dynamic**>, List<**CustomClass**>
 // Then I convert data value of list to specified type.
 IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], genericType);
Type-Type=typeof(IList);
//Type genericType=如何获取列表的类型。例如列表,列表,列表
//然后我将列表的数据值转换为指定的类型。
IList data=(IList)JsonConvert.DeserializeObject(此._dataSourceValues[i],genericType);
_dataSourceValues:列表中的值


如果列表类型是动态的(
list
),如何将列表类型强制转换为特定类型?

如果我正确理解您,您有一个
列表
,并且您希望创建一个具有动态对象的适当运行时类型的列表

是否需要以下帮助:

private void x(List<dynamic> dynamicList)
{
    Type typeInArgument = dynamicList.GetType().GenericTypeArguments[0];
    Type newGenericType = typeof(List<>).MakeGenericType(typeInArgument);
    IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], newGenericType);
}
private void x(列表动态列表)
{
类型typeInArgument=dynamicList.GetType().GenericTypeArguments[0];
Type newGenericType=typeof(列表)。MakeGenericType(typeInArgument);
IList data=(IList)JsonConvert.DeserializeObject(此._dataSourceValues[i],newGenericType);
}
另一方面,我认为您应该重新考虑代码的设计。我没有足够的上下文,但我很好奇为什么在这里使用dynamic。拥有一个
列表
基本上意味着您不关心传入列表的类型。如果你真的很喜欢这个类型(就像你在做序列化一样),也许你不应该使用dynamic。

private void x(List dynamicList)
 private void x(List<dynamic> dynamicList)
            {
                Type typeInArgument = dynamicList.GetType();
                Type newGenericType = typeof(List<>).MakeGenericType(typeInArgument);
                IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], newGenericType);
            }
{ 类型typeInArgument=dynamicList.GetType(); Type newGenericType=typeof(列表)。MakeGenericType(typeInArgument); IList data=(IList)JsonConvert.DeserializeObject(此._dataSourceValues[i],newGenericType); }
如果在编译时不知道类型,则不能(除非使用反射),即使使用反射,也不能将其强制转换为静态类型的对象。@MikeGoodwin您知道OP为什么要强制转换它吗?当你有一个动态对象的时候,我不明白为什么你需要投射它。这难道不是拥有动态、逃避强类型问题的主要原因吗?还有,为什么你认为反思没有帮助?谢谢你的回答。我发现,动态是一种对象类型(当我使用get-type方法时)。关于反思代码:我有服务来呈现报告,所以我需要以字符串形式将所有资源传递给它,这就是我使用上述代码的原因。因为工作的需要,我说不清楚。