2015-10-01 41 views
1

此方法有效,但它返回列表<object>當我真正想要的是列表<Resource>特定類型是資源時(和列表<YYY>特定類型是YYY時,等等)。如何正確返回投射IEnumerable

如何重新排列方法簽名以返回列表<specificType>?那麼,有沒有更好的方法來做到這一點?列表<object>中的項目在本程序集中從許多不同類型反序列化。我正在嘗試創建ActualType列表並將該列表返回給調用者。希望這是有道理的。

private static ICollection<object> GetSpecificTypeList(Dictionary<string, List<object>> objectListDictionary, Type specificType) 
{ 
    Contract.Requires(objectListDictionary != null); 
    Contract.Requires(specificType != null); 

    var typeFullName = specificType.FullName; 
    var typedCollection = (IList)Activator.CreateInstance(typeof(List<>).MakeGenericType(specificType)); 
    var collection = objectListDictionary.SingleOrDefault(q => q.Key.Equals(typeFullName)).Value; 
    foreach (var obj in collection) 
    { 
     typedCollection.Add(Convert.ChangeType(obj, specificType)); 
    } 

    return collection; 
} 

var resourceList = GetSpecificTypeList(package.FilesDictionary, typeof(Resource)); 

會動態幫助嗎?

+0

爲什麼所有的寫照嗎?爲什麼不只是通用的開始呢? 'private static List GetSpecificTypeList (Dictionary > objectListDictionary){...}'? –

回答

6

使該方法一般:

private static ICollection<T> GetSpecificTypeList<T>(Dictionary<string, List<object>> objectListDictionary) 
{ 
    Contract.Requires(objectListDictionary != null); 
    Contract.Requires(specificType != null); 

    var list = new List<T>(); 
    var collection = objectListDictionary.SingleOrDefault(q => q.Key.Equals(typeof(T).FullName)).Value; 
    foreach (var obj in collection.OfType<T>()) 
    { 
     list.Add(obj); 
    } 

    return list; 
} 
+0

我覺得'Dictionary > objectListDictionary'應該是'Dictionary > objectListDictionary' –

+0

@JamesR。他傳入的對象('package.FilesDictionary')是一個'Dictionary >' –

+0

@DaveZych,但考慮到以下Stanley的建議通過Dictionary > –

3

如何重新排列方法簽名以返回List<specificType>

使該方法一般:

private static ICollection<T> GetSpecificTypeList<T>(Dictionary<string, List<object>> objectListDictionary) 
{ 
    Contract.Requires(objectListDictionary != null); 
    Contract.Requires(specificType != null); 

    var typeFullName = typeof(T).FullName; 
    //var collection = objectListDictionary.SingleOrDefault(q => q.Key.Equals(typeFullName)).Value; 
    var collection = objectListDictionary[typeFullName]; 
    var typedCollection = collection.OfType<T>().ToList(); 

    return typedCollection; 
} 

現在您的調用語法是:

var resourceList = GetSpecificTypeList<Resource>(package.FilesDictionary); 

其他一些建議:

  • 考慮一個Dictionary<Type, List<object>代替 - 使用S atring識別一個類型可能會很棘手
  • 您甚至可以使用List<object>並使用list.OfType<T>進行過濾(假定每個對象集合的鍵都是它的類型。
+0

感謝您的其他建議。 –

1

這是我在使用收益回報和IEnumerable戴夫propsal,使懶惰評估的修改後的版本:

private static IEnumerable<T> GetSpecificTypeList<T>(Dictionary<string, List<object>> objectListDictionary) 
{ 
    Contract.Requires(objectListDictionary != null); 
    var collection = objectListDictionary.SingleOrDefault(q => q.Key.Equals(typeof(T).ToString())).Value; 
    foreach (var obj in collection) 
    { 
     yield return (T) Convert.ChangeType(obj, typeof(T)); 
    } 
}