如何清除动态对象中的值? [英] How to clear the values inside a dynamic object?

查看:251
本文介绍了如何清除动态对象中的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将数据集转换为动态集合并绑定它,这是正常工作。现在,当我需要添加一个新的对象是空的集合。我正在尝试的是获取Datagrid的ItemsSource并获取列表中的第一个对象。但它里面有一些价值。我如何删除值并使用反射来绑定空对象。



这是我的代码,

  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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆