繁体   English   中英

C#初学者问题

[英]C# Beginner problems

我有一个“Debug”类,它只是将信息打印到控制台等。从其他代码我希望能够调用其中的方法,但到目前为止它只是部分工作。

调用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”课程中,我有:

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");
        }
    }
}

您看到错误的原因是因为GetEventsLogged()返回一个intPrint()希望您传入一个string 因此,您需要从int返回到string并且您使用ToString()处于正确的轨道上。 这将做你想要实现的目标:

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

dc.Print()想要一个字符串参数, dc.GetEventsLogged()返回一个int 你需要ToString() int以使类型匹配。

int numberOfEventsLogged = dc.GetEventsLogged();

string numberOfEventsLoggedAsString = numberOfEventsLogged.ToString();

dc.Print(numberOfEventsLoggedAsString)

尝试dc.Print(dc.GetEventsLogged().toString())因为GetEventsLogged()是int类型而Print(string Message)正在寻找字符串输入。

您的方法Print需要String类型的参数。 当你调用dc.Print(dc.GetEventsLogged()) ,你实际上给了一个int因为你的方法GetEventsLogged()返回一个int

    public string GetEventsLogged()
    {
        return events_logged.ToString();
    }

暂无
暂无

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

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