【问题标题】:How to clear the values inside a dynamic object?如何清除动态对象内的值?
【发布时间】:2014-10-19 08:16:24
【问题描述】:

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

这是我的代码,

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

【问题讨论】:

  • 我不确定我是否理解您的问题。如果你使用反射来获取未知类型的属性,那么你可以使用反射来获取构造函数并实例化它。
  • 我只想使用这些属性创建一个空对象
  • 您在寻找Activator.CreateInstance(list[0].GetType())吗?
  • @SriramSakthivel 谢谢,我怎样才能为它里面的属性设置空值?
  • 空值是什么意思?你的意思是默认值?默认情况下,如果您的类没有在构造函数或字段初始化程序中设置任何内容,那么它只会是默认值,不是吗?

标签: c# wpf reflection silverlight-4.0 dataset


【解决方案1】:

如果你的未知类型有一些已知的构造函数,那么你可以使用反射来实例化它。

// 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]);

显然,当您没有简单的无参数构造函数时,这将不起作用。如果您知道类构造函数总是采用某个参数,例如整数值,那么您可以使用new Type[] { typeof(int) }new object[] { someIntValue } 修改上面的 sn-p。

但这是否会创建一个“空”对象取决于构造函数的行为。


如果您想设置一些属性,您可以遍历调用type.GetProperties() 返回的PropertyInfos,并使用适当的值调用SetValue

【讨论】:

    【解决方案2】:
    1. 获取该对象的类型并创建一个新对象,并将其添加到 列表,列表[0]

    2. 写一个函数,传递这个对象,获取它的类型,清除各个属性, 如果你知道它包含什么属性

    【讨论】:

      【解决方案3】:

      调用Activator.CreateInstance 创建新实例。然后使用PropertyInfo.SetValue 将字符串字段设置为空。

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

      请注意,如果类型没有无参数构造函数,Activator.CreateInstance 会抛出异常。

      【讨论】:

      • 'System.Reflection.PropertyInfo.SetValue(object, object, object[])'的最佳重载方法匹配
      • @Sajeetharan 根据documentation,有一个带有两个参数的方法。如果您使用不同的技术,没问题。只需使用p.SetValue(instance, string.Empty, null);
      • 谢谢,终于找到解决办法了
      猜你喜欢
      • 2012-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-06
      • 1970-01-01
      • 2011-05-18
      相关资源
      最近更新 更多