简体   繁体   English

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

[英]trouble converting function from vb to c#

I am trying to migrate myself to only using C# (was/am a vb.net guy) I am having trouble converting this vb.net function from a project Im migrating 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

holidaysFile is a text file that contains items like this; 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 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

any help appreciated, and streamreader may be better way to read this? 任何帮助表示赞赏,streamreader可能是更好的阅读方式?

You can do 你可以做

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

This matches the original: 这与原始匹配:

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

But it kills me to use a List like that unless there's a real need for it. 但是除非真正需要它,否则使用这样的List会使我丧命。 The code below will allow you to do lazy evaluation, supports only keeping one line in RAM at a time, and often still works with no changes to the calling code — many of the same benefits as using a StreamReader. 下面的代码将允许您进行延迟评估,一次仅支持在RAM中保留一行,并且通常仍可以在不更改调用代码的情况下正常工作-与使用StreamReader一样,具有许多相同的好处。 Note that it's also shorter, and can still be easily converted to a List if needed. 请注意,它也较短,如果需要,仍可以轻松转换为List。 While I'm here, since you're coming from a string, you might do better using the DateTime.Parse() method: 当我在这里时,由于您来自字符串,因此使用DateTime.Parse()方法可能会更好:

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

As a general rule, you're almost always better off writing code to return an IEnumerable<T> instead of a List<T> . 通常,编写代码返回IEnumerable<T>而不是List<T>几乎总是更好。 You have very little to lose, because you can always just append .ToList() to the end of such a function when you need, and much to gain in terms of easier refactoring from one underlying collection type to another and potential performance improvements by reducing RAM use or avoiding looping over items in the List it later turns out you never needed. 您几乎没有什么损失,因为您总是可以在需要时仅将.ToList()追加到此类函数的末尾,并且在从一种基础集合类型更容易地重构为另一种基础集合类型以及通过减少RAM的使用或避免循环遍历List中的项目,后来发现您根本不需要。

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

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