转换为动态类型变量的通用列表
我需要更改 List<*DynamicType*>
类型的动态变量的 Capacity
属性。 问题是,如果未指定变量类型,Activator
将返回 object
转换的变量,而不是正确的 List<*DynamicType*>
和最佳值我能做的就是将其转换为IList
:
DynamicTypeBuilder builder = new DynamicTypeBuilder() { ... };
Type dataType = builder.GenerateType(...);
Type listDataType = typeof(List<>).MakeGenericType(dataType);
IList list = (IList)Activator.CreateInstance(listDataType);
经过一番搜索,我只发现了一个技巧:
dynamic dynamicList = list;
dynamicList.Capacity = dataRowsCount;
虽然这在我的情况下是可以接受的,但我想知道是否还有另一种方法可以做到这一点。
I need to change the Capacity
property of the dynamic variable of type List<*DynamicType*>
.
The problem is that Activator
returns object
-casted variable if variable type is not specified instead of proper List<*DynamicType*>
and the best I can do is to cast it to IList
:
DynamicTypeBuilder builder = new DynamicTypeBuilder() { ... };
Type dataType = builder.GenerateType(...);
Type listDataType = typeof(List<>).MakeGenericType(dataType);
IList list = (IList)Activator.CreateInstance(listDataType);
After some searching I found only one hack:
dynamic dynamicList = list;
dynamicList.Capacity = dataRowsCount;
Though this would be acceptable in my case I wonder if there is another way to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用反射来完成此操作:
另一种方法是编写一个通用方法,以静态类型的方式执行您想要的所有操作,然后使用反射来调用那个。这是确保您只需要一个反射的便捷方法。
You can do it with reflection:
An alternative is to write a generic method which does everything you want in a statically typed way, and call that with reflection instead. That can be a handy way of making sure you only need one piece of reflection.
也许这更简单:
哪个应该使用正确的构造函数?
泛型和反射结合起来确实很痛苦。这里的
dynamic
黑客并不比通过反射设置它更难看(作为文字的魔术字符串,与未经验证的属性成员),并且dynamic
是内部优化和缓存的(每个-type),所以我不会有任何问题。如果您需要执行多个属性,您还可以使用dynamic
转换为泛型方法,以最大程度地减少丑陋:这将使用正确的
T
调用泛型方法代码>.仅对于 1 名成员而言不值得,但对于更复杂的场景可能有用。Perhaps this is simpler:
Which should use the correct constructor?
Generics and reflection are indeed a pain in combination. The
dynamic
hack here is no uglier than setting it via reflection (a magic string as a literal, vs an unverified property member), anddynamic
is internally optimised and cached (per-type), so I wouldn't have a problem with it. If you need to do more than just one property, you can also usedynamic
to flip into a generic method, to minimise the ugly:Which will invoke the generic method with the correct
T
. Not worth it just for 1 member, but it might be useful for more complex scenarios.