You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#如何将方法执行结果赋值给string[]或string[][]类型变量

代码调整方案

核心改动如下:

  • 修改原有GetString方法的返回值类型,取消直接打印逻辑,返回读取到的CSV内容
  • 主方法中定义两个独立变量分别存储timeline.csv和people.csv的读取结果,支持string[](存原始行)和string[][](存拆分后字段)两种存储格式

基础版:返回原始行的string[]格式

该版本保留每行原始内容,需要时再拆分字段使用:

using System;
using System.IO;

namespace TimeTress
{
    class Program
    {
        static void Main(string[] args)
        {
            // 两个变量分别存储两个CSV的所有行内容
            string[] timelineLines = GetString("../../../../timeline.csv");
            string[] peopleLines = GetString("../../../../people.csv");
        }

        static string[] GetString(string path)
        {
            if (File.Exists(path))
            {
                // 直接返回所有行组成的字符串数组
                return File.ReadAllLines(path);
            }
            else
            {
                // 原俄文提示意为「文件未找到,路径为xxx」,可替换为中文提示
                Console.WriteLine($"Файл не найден по пути {Path.GetFullPath(path)}");
                return Array.Empty<string>();
            }
        }
    }
}

进阶版:返回拆分后字段的string[][]格式

该版本直接将每行按分号拆分为字段数组,后续可以直接按索引取对应字段,无需额外拆分:

using System;
using System.IO;
using System.Linq;

namespace TimeTress
{
    class Program
    {
        static void Main(string[] args)
        {
            // 第一层索引对应行号,第二层索引对应字段序号
            // timeline的字段索引:0=事件日期,1=事件描述
            string[][] timelineData = GetSplittedCsv("../../../../timeline.csv");
            // people的字段索引:0=姓名,1=出生日期,2=死亡日期
            string[][] peopleData = GetSplittedCsv("../../../../people.csv");
        }

        static string[][] GetSplittedCsv(string path)
        {
            if (File.Exists(path))
            {
                return File.ReadAllLines(path)
                    .Select(line => line.Split(';', StringSplitOptions.RemoveEmptyEntries))
                    .ToArray();
            }
            else
            {
                Console.WriteLine($"Файл не найден по пути {Path.GetFullPath(path)}");
                return Array.Empty<string[]>();
            }
        }
    }
}

内容的提问来源于stack exchange,提问作者Ilya Kvashnin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 01:18:03