【问题标题】:How to make a function which returns Type <T>如何制作返回类型 <T> 的函数
【发布时间】:2015-02-06 23:09:28
【问题描述】:

C# .net 4.0

我创建了一个将 ArrayList 转换为 List 的函数

List<MatchBowlDetails> lstBowling = ConvertArrayListToList(BowlingTeamScore).Cast<MatchBowlDetails>().ToList(); 

public static List<Object> ConvertArrayListToList(CollectionClass paramcollection)
    {
        //Function use:
        //This function takes array List and return List<Type>
        //TODO

        return null;
}

正如您在此处看到的,我创建了一个将ArrayList 转换为List&lt;T&gt; 的函数

这里的BowlingTeamScoreMatchBowlDetails 类的集合,继承自CollectionClass,这使得ArrayList 类型的集合。

现在这里因为此函数返回 List&lt;Object&gt; 类型的对象,我想返回 List&lt;T&gt; 类型的 T,其中 TparamCollection.GetType();

所以新的用户代码将是:

List<MatchBallDetails> lstBowling = ConvertArrayListToList<BowlingTeamScore); // here no need to type cast back..

请建议如何做到这一点。

【问题讨论】:

    标签: c# arraylist collections type-conversion


    【解决方案1】:

    你的意思是这样的吗?

    public static List<T> ConvertArrayListToList<T>(CollectionClass paramcollection)
    {
        return paramcollection.Cast<T>().ToList(); 
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      • 2021-05-21
      • 2018-05-01
      • 1970-01-01
      相关资源
      最近更新 更多