2014-11-23 66 views
0

我通過循環一個對象的屬性,在這裏我要結束了加入的IEnumerable或的ObservableCollection到已有的ObservableCollection屬性(Object類型)。鑄造的ObservableCollection <Object>到的ObservableCollection <Type>哪裏類型是未知

這是我到目前爲止有:

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>

我對此感到非常沮喪,並且使用Google搜索半天以上,如果有人能夠幫助我,我將不勝感激。

+0

'TypeObject'是一個變量,而不是一個類型。它不能用作通用參數。 – Enigmativity 2014-11-23 09:27:12

回答

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); 
+0

而獲勝者是! 謝謝克里斯,我將不得不閱讀(動態)演員陣容,這正是我需要的。 – Johnson 2014-11-23 09:33:22

+0

@ Johnson11;是的,「動態」可以很有趣。我還添加了沒有「動態」的那個,它可能表現更好,並且更容易遵循。 – 2014-11-26 15:58:42

相關問題