使用内省在集合上设置标量值
我正在做类似以下问题的答案: 使用反射设置对象属性
动态设置对象属性的值。我有一个包含此类功能的函数,并且效果很好。但是,我想让它查看属性类型以查看它是否是某种集合并将值/对象添加到集合中。
我尝试做类似的事情: if (object is ICollection)
问题是 VS2010 希望我输入我不知道如何以编程方式执行的集合。
所以我想做的是像下面给定的 subject
是目标对象,value
是要设置的值:
public void setPropertyOnObject(object subject, string Name, object value)
{
var property = subject.GetType().GetProperty(Name)
// -- if property is collection ??
var collection = property.GetValue(subject, null);
collection.add(value)
// -- if propert is not a collection
property.SetValue(subject, value, null);
}
I am doing something like the answer on:
Set object property using reflection
Dynamically setting the value of a object property. I have a function wrapping this sort of functionality and it works great. However, I want to make it so that it looks at the property type to see if it is some sort of collection and add the value/object to the collection.
I tried to do something like: if (object is ICollection)
The problem is that VS2010 wants me to type the collection which I dont know how to do programatically.
So what I want to do is something like the following given subject
is the target object and value
is value to be set:
public void setPropertyOnObject(object subject, string Name, object value)
{
var property = subject.GetType().GetProperty(Name)
// -- if property is collection ??
var collection = property.GetValue(subject, null);
collection.add(value)
// -- if propert is not a collection
property.SetValue(subject, value, null);
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以动态检查类型化集合(并向其中添加项目),如下所示:
You can dynamically check a typed collection (and add an item to it) thusly: