2013-07-18 62 views
2

我有一個「調試」類,它只是將信息打印到控制檯等。從其餘代碼我想能夠調用其中的方法,但到目前爲止它只是部分工作。C#初學問題

調用dc.Print()工作正常,但只要我打電話dc.Print(dc.GetEventsLogged())我得到一個紅線與消息

「的最佳重載的方法匹配具有一些無效參數」以及參數1:不能從'int'轉換爲'string'。

基本上:爲什麼我的論點dc.Print錯誤?另外,我能做些什麼「不能從int轉換爲字符串我試過的ToString但沒有任何工作

這是我的?‘Debug.cs’類:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 


namespace Test 
{ 
    public class Debug 
    { 
     private int events_logged; 

     public Debug() 
     { 
      events_logged = 0; 
     } 

     public void Print(string Message) 
     { 
      Console.WriteLine("[" + DateTime.UtcNow + "] " + Message); 
      events_logged++; 
     } 


     public int GetEventsLogged() 
     { 
     return events_logged; 
     } 
    } 
} 

而且在我的「Program.cs的」 I類有:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 

namespace Test 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      Debug dc = new Debug(); 
      dc.Print("Test"); 
     } 
    } 
} 

回答

7

您所看到的錯誤是因爲GetEventsLogged()返回intPrint()希望你在string通過。因此,您需要從int返回到string,並且您在ToString()的正確軌道上。這將做你想要達到的目標:

dc.Print(dc.GetEventsLogged().ToString()); 
+1

謝謝,這工作正常:)我試圖.ToString沒有() – user9993

+1

沒問題,歡迎來到StackOverflow!你會在這裏找到很多有幫助的人,我們都必須從某個地方開始!你能否請點擊這個答案旁邊的TICK標記爲「已解決」,如果他們有同樣的問題,這將幫助其他人發現這個問題。 – Belogix

2

dc.Print()想要一個字符串參數和dc.GetEventsLogged()返回int您需要ToString()int,這樣類型的比賽

int numberOfEventsLogged = dc.GetEventsLogged(); 

string numberOfEventsLoggedAsString = numberOfEventsLogged.ToString(); 

dc.Print(numberOfEventsLoggedAsString) 
0
public string GetEventsLogged() 
    { 
     return events_logged.ToString(); 
    } 
1

嘗試dc.Print(dc.GetEventsLogged().toString())因爲GetEventsLogged()爲int類型和Print(string Message)尋找字符串輸入的。

1

您的方法Print需要參數類型String。當您致電dc.Print(dc.GetEventsLogged())時,您實際上會給出int,因爲您的方法GetEventsLogged()返回int