DateTime.Compare 在 C# 中

DateTime.Compare in c#

我目前正在尝试将我的 vb.net 代码的一部分转换为 C#,但我似乎无法获得正确的语法。

我的vb.net代码是

Private Sub board(days As Integer, name As String)

Dim dcount As Integer = 0
Dim counter As Integer = 0


    If My.Computer.FileSystem.FileExists("pathway" + name) AndAlso Not File.ReadAllText("pathway" + name).Length = 0 Then

        Dim d As List(Of String) = File.ReadAllLines("pathway" + name).ToList
        Dim line As String = d(0)

        While counter <> d.Count
            line = d(counter)


            If DateTime.Compare(line.Substring(0, line.LastIndexOf(",")), Now.AddDays(days).ToString("MM/dd/yyyy")) < 0 Then
                dcount += 0
                counter += 1
            Else
                dcount += 1
                counter += 1

            End If
        End While
    End If

vb.net 代码运行正常,但我下面的 C# 给出了错误:

运算符“<”不能应用于 'string' 和 'int'

类型的操作数

错误所在的行是:

if (DateTime.Compare(line.Substring(0, line.LastIndexOf(",")), DateTime.Now.AddDays(days).ToString("MM/dd/yyyy") < 0)) {

整个部分在下面

  private void board(int days, string name){


 int dcount = 0;
        int counter = 0;

if (File.Exists(@"pathway" + name) && File.ReadAllText(@"pathway" + name).Length != 0)
        {
            List<string> d = File.ReadAllLines(@"pathway" + name).ToList();
            string line = d[0];

            while (counter != d.Count)
            {
                line = d[counter];
                // compares the current date to the amount of days you put in the days integer
                if (DateTime.Compare(line.Substring(0, line.LastIndexOf(","), DateTime.Now.AddDays(days).ToString("MM/dd/yyyy") < 0) {
                    counter++;
                } else
                {
                    dcount++;
                    counter++;
                }
            }
        } 
 }

非常感谢你们能给我的任何帮助

DateTime.Compare只能用于比较DateTime个对象。

在VB.NET中有隐式类型转换,但在c#中你必须是显式的。

而不是

if (DateTime.Compare(line.Substring(0, line.LastIndexOf(",")), DateTime.Now.AddDays(days).ToString("MM/dd/yyyy") < 0)) 
{
    //Do something
}

你需要写类似

的东西
var d1 = DateTime.Parse(line.Substring(0, line.LastIndexOf(","));
var d2 = DateTime.Now.AddDays(days);
if (DateTime.Compare(d1, d2) < 0) 
{
    //Do something
}

如果你真的想把所有内容都写在一行中,你可以这样做,但它可能有点难以阅读:

if (DateTime.Compare(DateTime.Parse(line.Substring(0, line.LastIndexOf(",")), DateTime.Now.AddDays(days) < 0) 
{
    //Do something
}