且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何清除动态对象中的值?

更新时间:2023-11-18 08:35:46

调用 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.