[英]c#: Convert object to a generic list
I've got a data structure in which a variable is of type object
. 我有一个数据结构,其中变量是object
类型。 However, I know during runtime this object will be definitely a List<T>
, where T
should cover multiple cases (eg, int
, string
, ...). 但是,我知道在运行时此对象肯定是List<T>
,其中T
应该涵盖多种情况(例如int
, string
,...)。 In the following code, I'd like to use List<T>
-specific functionality, such as Linq functions. 在以下代码中,我想使用特定于List<T>
功能,例如Linq函数。
With the following check, I make sure, it's a list: 通过以下检查,我确定它是一个列表:
if (constantExpression.Value.GetType().GetGenericTypeDefinition() == typeof(List<>))
{
// Want to use Linq here
}
Is this possible? 这可能吗? Unfortunately, I've found nothing helpful on the Web. 不幸的是,我发现网上没有任何帮助。
If it's ok for you to handle your list as a List<object>()
you can do the following: 如果可以将列表作为List<object>()
,则可以执行以下操作:
var listOfObjects = ((IEnumerable)constantExpression.Value).Cast<object>();
That's far from perfect but it's probably the best you can get if you don't want to resort to using reflection or using dynamic
, as suggested in the comments. 这远非完美,但如果您不想像评论中所建议的那样使用反射或使用dynamic
,那可能是最好的选择。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.