C# 扩展泛型列表类型的方法

C# 扩展泛型列表类型的方法,c#,.net,extension-methods,C#,.net,Extension Methods,TL;DL:简化方法此列表。。。要创建此列表。。。对于通用列表 我想写一个扩展方法,允许我获取任何类型对象列表中所有属性p的值 到目前为止,我采用了这种方法: public static T[] selectAll<T, U>(this List<U> list, string property) { List<T> r = new List<T>(); // prepare a list of values of the

TL;DL:简化方法此列表。。。要创建此列表。。。对于通用列表

我想写一个扩展方法,允许我获取任何类型对象列表中所有属性p的值

到目前为止,我采用了这种方法:

public static T[] selectAll<T, U>(this List<U> list, string property)
{
    List<T> r = new List<T>();          // prepare a list of values of the desired type to be returned
    foreach(object o in list)
    {
        Type mt = o.GetType();          // what are we actually dealing with here? (List of what?)   <-- This should be the same as Type U
        IList<PropertyInfo> props = new List<PropertyInfo>(mt.GetProperties());          // Get all properties within that type
        foreach(PropertyInfo p in props)
        {
            if (p.Name == property)                   // Are we looking for this property?
                r.Add((T)p.GetValue(o, null));        // then add it to the list to be returned
        }
    }
    return r.ToArray();
}
未绑定泛型名称含义列表的意外使用


列表无法注册为所有类型列表的扩展名看起来您正在为参数寻找非通用版本-IList或IEnumerable都可以

public static T[] selectAll<T>(this IList list, string property){
    ...
}
什么地方出了问题

虽然我已经用这两种方法导入了

System.Collections.Generic

专门的,专门的

我不知道那些名称空间部分继承自的类实际上在System.Collections中。我以为我得到的是一块蛋糕的两半,而我得到的是两份馅料,而没有得到蛋糕皮

因此,当我尝试使用IEnumerable时,例如,我亲爱的、值得信赖的IDE Visual Studio 2017不会接受没有类型指示器的IDE

对于任何通过谷歌来到这里的人来说,都有同样的问题:

同时使用.Generic和.Specialized将不会涵盖您, 集合类型从中提取的大部分内容都在父系统System.Collections中

我可以为你服务

不过,就我的上述情况而言

public static T[] selectAll<T>(this IEnumerable<object> list, string property){
    ...
}
同样有效,但IList未能注册为列表的扩展

空间和概念的命名可能会产生误导:

我认为ILIST是专用的类型,ILIST是通用的,因为它适用于所有的S-但在C世界中。反过来说:IList本身被认为是非泛型的——泛型的问题……是从外部而不是从内部来处理的——它包含了什么或可以包含什么——像我这样的高级程序员可能会凭直觉出错

总之:

集合由多个类组成

直觉上,泛型集合被称为非泛型集合,因为可以这样说的较低级别的幂

System.Collections.IEnumerable似乎适用于所有类型的列表

阅读官方文件通常是有用的。等待一般地还是具体地?哦,谁知道呢


尝试使用IEnumerable非泛型。例如,我做了一个快速测试,它似乎与字符串[]一起工作。@glenebob是的,我只是用IEnumerable自己尝试了一下,这很有效。仍然在寻找坏的边缘案例,看看它有多强大,兄弟。。。我没有看到这种可能性,因为我没有使用System.Collections本身——谢谢你的正确答案。我的备选答案详细说明了让我困惑的问题:
public static T[] selectAll<T>(this IList list, string property){
    ...
}
public static T[] selectAll<T>(this IEnnumerable list, string property){
    ...
}
public static T[] selectAll<T>(this IEnumerable<object> list, string property){
    ...
}