将ObservableCollection <object>转换为ObservableCollection <type>其中type未知</type> </object>

时间:2014-11-23 08:59:45

标签: c#

我正在遍历一个对象(类型为Object)属性,我希望最终在已经存在的ObservableCollection属性中添加IEnumerable或ObservableCollection。

这是我到目前为止所做的:

var PropList = TempObject.GetType().GetRuntimeProperties().ToList();
foreach (PropertyInfo ShowProp in PropList) 
{
   if (ShowProp.GetCustomAttribute<MarkedAttribute>() != null) 
   {
      Type TypeObject = ShowProp.PropertyType.GenericTypeArguments[0];

      // GetCollectionMethod returns a ObservableCollection<object>
      // The code below obviosuly doesn't work, but that is what i want to achieve.
      ObservableCollection<TypeObject> NewList = new ObservableCollection<TypeObject (GetCollectionMethod());

      TempObject.GetType().GetRuntimeProperty(ShowProp.Name).SetValue(TempObject, NewList);
   }
}

正如您所看到的,我坚持将ObservableCollection<object>投射到ObservableCollection<TypeObject>

我尝试使用Activator类创建一个新的ObservableCollection,它运行良好。代码如下:

    // This creates an ObservableCollection<TypeObject>, but as soon as i fill it
    // with a IENumerable<Object> it get's converted into a ObservableCollection<Object>

    var listType = typeof(ObservableCollection<>);
    var concreteType = listType.MakeGenericType(TypeObject);
    var newList = Activator.CreateInstance(concreteType);
    newList = GetCollectionMethod();

在上面的示例中,我将GetCollectionMethod()改为IENumerable<Object>,但它只更改了我的ObservableCollection的原始<TypeObject>

我对此感到非常沮丧并且谷歌搜索超过半天,如果有人可以帮助我,我将不胜感激。

1 个答案:

答案 0 :(得分:1)

您可以将元素复制到新创建的集合中,如下所示:

foreach(var elem in GetCollectionMethod())
    ((dynamic)newList).Add((dynamic)elem);

或者,你可以试试这个:

var newList = (IList)Activator.CreateInstance(concreteType);

foreach(var elem in GetCollectionMethod())
    newList.Add(elem);