[英]How to get the type of a dynamic object in C#?
我有一个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 specified type.
IList data = (IList)JsonConvert.DeserializeObject(this._dataSourceValues[i], genericType);
_dataSourceValues:列表中的值
如果List的类型是动态的( List<dynamic>
),如何将列表类型转换为特定类型?
如果我理解正确你有一个List<dynamic>
并且你想创建一个具有动态对象的相应运行时类型的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);
}
另外,我认为您应该重新考虑代码的设计。 我真的没有足够的上下文,但我很好奇为什么你在这里使用动态。 拥有List<dynamic>
基本上意味着你不关心传入列表的类型。 如果你真的关心这个类型(看起来像你在做序列化一样)也许你不应该使用动态。
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.