2017-03-10 47 views
-4

如何將遞歸時間添加到timedate或時間跨度值?將日期時間值添加到以前的日期時間值

我已經試過這一點,但它給了我錯誤:

'A local variable named 'total' cannot be declared in this scope because it would give a different meaning to 'total, which is already in used in a 'parent or current' scope to denote something else'

private void button5_Click(object sender, EventArgs e) 
     { 
      int a = 0; 
      string path = @"C:\Users\Public\WriteLines.txt"; 
      using (StreamReader sr = new StreamReader(path)) 
      { 
       string line; 
       string[] lines = new String[500]; 

       DateTime now = DateTime.Now; 
       TimeSpan total = now - now; 
       int temp=0; 

       while ((line = sr.ReadLine()) != null) 
       { 
        lines[a] = line; 
        a++; 

       } 

       while (temp < a) 
       { 

        TimeSpan difference = Convert.ToDateTime(lines[temp+1]) - Convert.ToDateTime(lines[temp]); 
        TimeSpan total = total + difference; // <----ERROR HERE 
        Console.WriteLine(total); 
        Console.WriteLine(difference); 
        temp = temp + 2; 
       } 

      } 
     } 

也就是有沒有更好的辦法,以日期時間值設置爲零,這樣我可以遞歸增加值?

回答

0

你不能這樣做,因爲你已經有一個具有相同名稱的變量,與其他一些變量名替換,

TimeSpan newTotal = total + difference; 
Console.WriteLine(newTotal); 

更好的辦法是總前去除入庫時間,這樣你就不必再重複,

total = total + difference; 
    Console.WriteLine(total); 
3

您在方法中定義了「總數」兩次。你有沒有嘗試從第二個定義中刪除'TimeSpan'?

0

如錯誤所述,變量已經定義。在同一個變量的工作,或宣佈一個新的與其他名字:

total = total + difference; 

TimeSpan total2 = total + difference;