通过反射访问数组
我在某个对象中创建了类型化数组:
maket.GetType()
.GetProperty(q.xmltags)
.SetValue(maket,Array.CreateInstance(q.xmltag),0
), null);
这里我得到了该数组:
var tag = maket.GetType().GetProperty(q.xmltags).GetValue(maket, null);
现在我想向该数组添加一些元素,我尝试这样的代码:
dynamic temp = tag;
tag = temp.ToList().Add(test).ToArray();
显然它不起作用。我怎样才能正确地做到这一点?
I created typed array in some object:
maket.GetType()
.GetProperty(q.xmltags)
.SetValue(maket,Array.CreateInstance(q.xmltag),0
), null);
Here i get that array:
var tag = maket.GetType().GetProperty(q.xmltags).GetValue(maket, null);
Now i want to add some element to that array, i try such code:
dynamic temp = tag;
tag = temp.ToList().Add(test).ToArray();
Obviously it doesn't work. How can i do it properly?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
如果您打算使用 LINQ 帮助程序,例如:(
然后使用反射将其设置回属性) - 但是,这是一种扩展数组的非常昂贵的方法(至少,一旦重复几次) 。如果您可以将属性更改为列表而不是数组,则只需使用:(
无需事后“设置”)
If you are set on using the LINQ helpers, something like:
(then use reflection to set that back against the property) - however, this is a really expensive way to expand an array (at least, once it is repeated a few times). If you can change the property to be a list instead of an array, you can just use:
(with no need to "set" afterwards)
您的代码正在获取一个数组,将其转换为列表,然后向该列表添加一个元素。存储在属性中的原始数组保持不变。尝试使用以下命令将新数组设置回属性中:
Your code is getting an array, converting it to a list and then adding an element to that list. The original array stored in the property stays unmodified. Try setting your newly array back in the property using:
也许无类型数组列表会很有用
maybe untyped array list can be useful