代码之家  ›  专栏  ›  技术社区  ›  Rilcon42

CsvHelper对象引用未设置为对象的实例(GetRecords问题)

  •  -1
  • Rilcon42  · 技术社区  · 7 年前

    我在跟踪 this example . 据我所知 GetRecords 当我向 GetHist 终点,但我不明白为什么。

    我查过了:

    1. 我的数据遵循c#类的精确命名约定(我从csv中复制了名称,以在c#中创建变量名)
    2. 文件输入路径正确。
    3. 即时消息使用最新版本的CsvHelper(12.1.0)

    GetData调用的堆栈跟踪:

    “”位于CsvHelper.CsvReader.GetRecordsT+MoveNext()\r\n位于System.Collections.Generic.LargeArrayBuilder 1.AddRange(IEnumerable 在System.Collections.Generic.EnumerableHolpers.ToArray[T](IEnumerable)上的1项 1 source)\r\n at System.Linq.Enumerable.ToArray[TSource](IEnumerable 1源文件\r\n位于System.Linq.SystemCore_EnumerableDebugView`1.get_Items()“

    我的代码:

    using System;
    using System.Collections.Generic;
    using System.IO;
    using System.Linq;
    using System.Threading.Tasks;
    using CsvHelper;
    using Microsoft.AspNetCore.Hosting;
    using Microsoft.AspNetCore.Mvc;
    
    public class DataController : Controller
    {
    
        private readonly IHostingEnvironment _hostingEnvironment;
    
        public DataController(IHostingEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }
    
        [HttpGet("[action]")]
        public IEnumerable<OHLCData> GetHist()
        {
            var v=OHLCData.GetData(_hostingEnvironment);
            return v;
        }
    
        public class OHLCData
        {
            string time;
            double oask, hask, lask, cask, obid, hbid, lbid, cbid;
            int volume;
    
            //@TODO: shouldnt pass it to this class from controller, should set in startup and read in this method
            public static IEnumerable<OHLCData> GetData(IHostingEnvironment _hostingEnvironment)
            {
                string filepath = Path.Combine(_hostingEnvironment.WebRootPath, "EUR_USD.csv");
                using (var reader = new StreamReader(filepath))
                using (var csv = new CsvReader(reader))
                {
                    return csv.GetRecords<OHLCData>();
                }
            }
        }
    }
    
    1 回复  |  直到 7 年前
        1
  •  0
  •   Rilcon42    7 年前

    刚在另一本书中找到答案 SO post . 我需要声明属性而不是字段才能使对象映射正常工作。ie更改 string time; 以及其他 public string time {get;set;}