繁体   English   中英

将功能从vb转换为c#时遇到麻烦

[英]trouble converting function from vb to c#

我正在尝试将自己迁移到仅使用C#(以前是vb.net的人),我在从项目中转换此vb.net函数时遇到问题,我正在迁移到C#

Public Shared Function GetHolidays(ByVal holidaysFile As String) As List(Of Date)
    Dim sAllDates() As String = File.ReadAllLines(holidaysFile)
    Return (From sDate In sAllDates Select CDate(sDate)).ToList()
End Function

holidayFile是一个文本文件,其中包含以下内容;

01/01/2015 01/19/2015 02/16/2015 04/03/2015 05/25/2015 07/03/2015 09/07/2015 11/26/2015 12/25/2015

任何帮助表示赞赏,streamreader可能是更好的阅读方式?

你可以做

public static List<DateTime> GetHolidays(string holidaysFile)
{
    string[] sAllDates = File.ReadAllLines(holidaysFile);
    return (from sDate in sAllDates select Convert.ToDateTime(sDate)).ToList();
}

这与原始匹配:

public static List<DateTime> GetHolidays(string holidaysFile)
{
    return File.ReadAllLines(holidaysFile).Select(d => Convert.ToDateTime(d)).ToList();
}

但是除非真正需要它,否则使用这样的List会使我丧命。 下面的代码将允许您进行延迟评估,一次仅支持在RAM中保留一行,并且通常仍可以在不更改调用代码的情况下正常工作-与使用StreamReader一样,具有许多相同的好处。 请注意,它也较短,如果需要,仍可以轻松转换为List。 当我在这里时,由于您来自字符串,因此使用DateTime.Parse()方法可能会更好:

public static IEnumerable<DateTime> GetHolidays(string holidaysFile)
{
    return File.ReadLines(holidaysFile).Select(d => DateTime.Parse(d));
}

通常,编写代码返回IEnumerable<T>而不是List<T>几乎总是更好。 您几乎没有什么损失,因为您总是可以在需要时仅将.ToList()追加到此类函数的末尾,并且在从一种基础集合类型更容易地重构为另一种基础集合类型以及通过减少RAM的使用或避免循环遍历List中的项目,后来发现您根本不需要。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM