c# - 返回通用列表

标签 c# generics collections generic-method

我试图在从文件加载值后返回一个通用列表。然而,在多次摆弄类型操作之后,我仍然无法让它同意我的看法。代码如下;我的问题是:

  1. 我是否需要像下面开始的那样识别每种键类型,还是有更快的方法?我看到“where T: ...”在这里可能是相关的,但如果可能的话,我想允许 DateTime、int、string、double 等,但我不知道如何使用“where”。
  2. 为什么我不能将 DateTime 项添加到日期时间列表中?
  3. 当我尝试获取类型 (listType) 时,这似乎超出了范围。即使我在上面一行中使用它的地方声明了类型,它也说不存在这样的对象。

非常感谢你的想法

public static List<T> FileToGenericList<T>(string FilePath, int ignoreFirstXLines = 0, bool stripQuotes = true)
{
    List<T> output = new List<T>();

    Type listType = output.GetType().GetGenericArguments()[0];

    try
    {
        using (StreamReader stream = new StreamReader(File.Open(FilePath, FileMode.Open)))
        {
            string line;
            int currentLine = 0;

            while ((line = stream.ReadLine()) != null)
            {
                // Skip first x lines
                if (currentLine < ignoreFirstXLines) continue;

                // Remove quotes if needed
                if (stripQuotes == true)
                {
                    line = line.Replace(@"""", @"");
                }

                // Q1 - DO I HAVE TO HAVE THIS FOR EACH TYPE OR IS THERE A QUICKER WAY
                if (listType == typeof(System.DateTime))
                {
                    DateTime val = new System.DateTime();
                    val = DateTime.Parse(line);

                    // Q2 ERROR: 'Argument type is not assignable to parameter type 'T''                    
                    output.Add(val);

                    // For some reason the type 'listType' from above is now out of scope when I try a cast
                    output.Add((listType)val);
                }
                if (listType == typeof(System.String))
                {
                    //DateTime val = new System.DateTime();
                    //val = DateTime.Parse(line);
                    //output.Add(val.ToString());
                }

                // Continue tracking for line skipping purposes
                currentLine++;
            }
        }
    }
    catch (Exception ex)
    {
        throw new Exception("Error - there was a problem reading the file at " + FilePath + ".  Error details: " + ex.Message);
    }    
    return output;
}

最佳答案

与其将解析逻辑编码到 FileToGenericList 方法中,我认为更简洁、更灵活的方法是重构它并将其作为 lambda 传递。这是一个演示此方法的快速控制台应用程序:

class Program
{
    static void Main(string[] args)
    {
        // second argument is a lambda that describes how to convert the line into the type you require
        var dateList = FileToGenericList<DateTime>("dates.txt", DateTime.Parse);
        var stringList = FileToGenericList<string>("strings.txt", s => s);
        var intList = FileToGenericList<int>("integers.txt", Int32.Parse); 

        Console.ReadLine();
    }

    static List<T> FileToGenericList<T>(string filePath, Func<string, T> parseFunc, int ignoreFirstXLines = 0, bool stripQuotes = true)
    {
        var output = new List<T>();

        try
        {
            using (StreamReader stream = new StreamReader(File.Open(filePath, FileMode.Open)))
            {
                string line;
                int currentLine = 0;

                while ((line = stream.ReadLine()) != null)
                {
                    // Skip first x lines
                    if (currentLine < ignoreFirstXLines)
                        continue;

                    // Remove quotes if needed
                    if (stripQuotes == true)
                        line = line.Replace(@"""", @"");

                    var parsedValue = parseFunc(line);
                    output.Add(parsedValue);
                    currentLine++;
                }
            }
        }
        catch (Exception ex)
        {
            throw new Exception("Error - there was a problem reading the file at " + FilePath + ".  Error details: " + ex.Message);
        }    
        return output;
   }
}

关于c# - 返回通用列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10275148/

相关文章:

c# - 将 "dynamic"关键字与 __ComObject 一起使用时 RuntimeBinder 中的泄漏

Java:泛型语法

javascript - 从模型中检索 Backbone 集合并将其保留为集合

c# - 检查是否在 gridview 中修改了行

c# - 如何通过互联网实现发布/订阅通信

java - 在 Java 中使用泛型存储公共(public)父类(super class)型

Java泛型-使用未知类的成员方法

.net - .NET 3.5 中超过 100 万个有序集合的推荐数据结构

java - 如何在运行时根据用户/程序员的需要自动增加数组的大小?

c# - 枚举哈希集并从中删除元素