如何正确返回IEnumerable

Rob*_*err 1 c# generics casting

这个方法有效,除了它返回List <object>当我真正想要的是List <Resource>当specificType是Resource(和List <YYY>当specificType是YYY时,依此类推).

如何重新排列方法签名以返回List <specificType>?那么,有更好的方法吗?List <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));
Run Code Online (Sandbox Code Playgroud)

动态有帮助吗?

Dav*_*ych 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;
}
Run Code Online (Sandbox Code Playgroud)