【发布时间】:2020-12-14 16:50:31
【问题描述】:
我有各种各样的类,它们具有实现IEnumerable 的各种属性(例如IEnumerable<string>、IEnumerable<bool>、IEnumerable<enum> 等)。我正在尝试编写一些代码来过滤这些属性的值(例如,如果值为{ "one", "two", "three" },我可能想过滤.Contains("t") 的位置)。
这是我所拥有的精髓:
class MyObject
{
public IEnumerable<string> stringProp { get; set; } = new[] { "one", "two", "three" };
public IEnumerable<bool> boolProp { get; set; } = new[] { true, false, true };
public IEnumerable<int> intProp { get; set; } = new[] { 1, 2, 3 };
}
public static void Main(string[] args)
{
MyObject obj = new MyObject();
foreach (PropertyInfo prop in typeof(MyObject).GetProperties())
{
prop.SetValue(obj, (prop.GetValue(obj) as IEnumerable<dynamic>).Where(val => val != null));
}
}
问题是,当我尝试将值设置回对象 (property.SetValue) 时,会引发错误,因为新值是 IEnumerable<object>。
Object of type 'System.Linq.Enumerable+WhereArrayIterator`1[System.Object]' cannot be converted to type 'System.Collections.Generic.IEnumerable`1[System.String]'
我尝试过Convert.ChangeType,但这不起作用,因为IEnumerable 没有实现IConvertible。
我该如何做到这一点?为什么 LINQ Where 查询将 IEnumerable<dynamic> 更改为 IEnumerable<object>?
【问题讨论】:
-
能否请您添加错误和minimal reproducible example ?
-
另外,转换类型的不是
Where,而是compiler -
IEnumerable
是 IEnumerable -
100 次中有 99 次,使用
dynamic会为它解决的每个问题多产生 2 个问题。 -
我添加了一个最小的可重现示例
标签: c# reflection types propertyinfo dynamictype