How to clear the values inside a dynamic object?

2019-09-10 16:55发布

问题:

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();

回答1:

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.



回答2:

If your unknown type has some known constructor then you can instantiate it using reflection.

// gets the Type
Type type = list[0].GetType(); 

// gets public, parameterless constructor
ConstructorInfo ci = type.GetConstructor(new Type[0]);

// instantiates the object
object obj = ci.Invoke(new object[0]);

Obviously that won't work when you don't have a simple parameterless constructor. If you know that the class constructor always takes a certain parameter, for example an integer value then you could modify the snippet above with new Type[] { typeof(int) } and new object[] { someIntValue }.

But whether this will create an "empty" object or not depends on the behaviour of the constructor.


If you then want to set some properties you can iterate over the PropertyInfos returned by calling type.GetProperties() and call SetValue with the appropriate value.



回答3:

  1. Get the type of that object and create new one, and add it to the list, list[0]

  2. Write a Function, pass this object, get its type, clear individual properties, if you know what properties it contains