为了账号安全,请及时绑定邮箱和手机立即绑定

通用List <>类型的扩展方法

通用List <>类型的扩展方法

C#
翻阅古今 2021-05-12 18:34:16
简化method<returnType, ListType>(this List<ListType>, ...)到method<returnType>(this List<anyType>, ...)了泛型列表我正在寻找一种扩展方法,该方法允许我获取(任何类型的对象)列表中所有属性“ 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();}因为您不能简单地拥有未知的返回类型,所以我理解有必要在方法调用中指出返回类型,例如:List<Control> SomeListOfControls = ...string[] s = SomeListOfControls.selectAll<细绳, Control>("Text");但是,由于该列表中项目的类型与该方法无关,因此我想从方程式中消除Type变量。我希望我可以简单地打电话List<Control> SomeListOfControls = ...string[] s = SomeListOfControls.selectAll<string>("Text"); <-您知道该列表由什么组成>>。例如。但我想不出一种方法来做到这一点。即使在编译之前,我也可以看到public static T[] selectAll<T>(this List<> list, string property)是Unexpected use of an unbound generic name(含义List<>)。并且List<object>不能注册为各种扩展名List<?extends object>,可以这么说。如果可能的话,我该如何做呢?PS:似乎可能存在一种“本机”方式(通常是.net甚至C#),该方式是从可能具有T型属性P的集合中检索<T> P的集合-我无法弄清楚使用select和所有...但是如果有的话,我很乐意了解:)
查看完整描述

2 回答

?
胡说叔叔

TA贡献1804条经验 获得超8个赞

像你看起来是在寻找非通用版本的参数-无论是IList或IEnumerable将工作


public static T[] selectAll<T>(this IList list, string property){

    ...

}


查看完整回答
反对 回复 2021-05-21
?
ABOUTYOU

TA贡献1812条经验 获得超5个赞

后果(哪里出了问题)


虽然我都输入了(using)


System.Collections.Generic



System.Collections.Specialized,


我不知道这些命名空间部分继承的类实际上在中System.Collections。我以为我要得到两半蛋糕,而我却得到两个馅而又没有外壳。


因此,例如,当我尝试使用IEnumerable时,我亲爱且可信赖的IDE(Visual Studio 2017)在没有Type指示器的情况下不会接受它。


对于通过Google遇到同样问题的任何人:


同时使用这两种方法.Generic并.Specialized不会覆盖您,集合类型的很多借鉴都来自父级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){

    ...

}

效果也一样(而未IList<object>注册为扩展名List<?>


空间和概念的命名可能会引起误解:


我会认为IList<Type>是专门的(按类型)和IList泛型的(因为它适用于所有<Type>s)-但是在C#世界中,这是相反的:IList本身被认为是“非泛型的”-泛型的问题...内在性是从外部(在上下文中如何处理)而不是从内部(它包含(或可以包含)什么)来处理-像我这样的高级程序员可能会直觉上出错。


总之:

  • System.Collections包含的不仅是其类的总和

  • 直观地将泛型集合称为非泛型集合,因为这样说的是较低级别的能力

  • System.Collections.IEnumerable 似乎适用于各种列表

  • 阅读官方文档通常很有用。(等等...一般还是专门?哦,谁知道了:P)


查看完整回答
反对 回复 2021-05-21
  • 2 回答
  • 0 关注
  • 216 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信