如何清除动态对象中的值? [英] How to clear the values inside a dynamic object?
问题描述
这是我的代码,
IEnumerable< object> collection = this.RetrieveGrid.ItemsSource.Cast< object>();
列表< object> list = collection.ToList();
//我需要清除list [0]中的值
object name = list [0];
//这里我构建对象的属性,现在我需要使用这些属性创建一个空对象并将其添加到列表中
PropertyInfo [] pis = list [0] .GetType()。 GetProperties();
调用 Activator.CreateInstance
创建新的实例。然后使用 PropertyInfo.SetValue
将字符串字段设置为空。
类型requiredType = list [0] .GetType();
对象实例= Activator.CreateInstance(requiredType);
PropertyInfo [] pis = requiredType.GetProperties();
foreach(p p中的var p)
{
if(p.PropertyType == typeof(string))
{
p.SetValue(instance,string.Empty );
}
}
请注意 Activator。如果类型没有无参数的构造函数,CreateInstance
将抛出异常。
I am converting dataset to a Dynamic collection and binding it, this is working fine.Now when i need to add a new object which is empty to the collection . what i am trying is getting the ItemsSource of the datagrid and getting the first object inside the list. But it has some values inside it. How can i remove the values and bind a empty object using reflection.
Here is my code,
IEnumerable<object> collection = this.RetrieveGrid.ItemsSource.Cast<object>();
List<object> list = collection.ToList();
//i need to clear the values inside list[0]
object name = list[0];
//here i build the properties of the object, now i need to create an empty object using these properties and add it to the list
PropertyInfo[] pis = list[0].GetType().GetProperties();
Call Activator.CreateInstance
to create new instance. Then use PropertyInfo.SetValue
to set the string fields to empty.
Type requiredType = list[0].GetType();
object instance = Activator.CreateInstance(requiredType);
PropertyInfo[] pis = requiredType.GetProperties();
foreach (var p in pis)
{
if (p.PropertyType == typeof(string))
{
p.SetValue(instance, string.Empty);
}
}
Do note that Activator.CreateInstance
throws exception if the type doesn't have parameterless constructor.
这篇关于如何清除动态对象中的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!