如何解决此错误“错误CS1503:参数1:无法从'void'转换为'bool'”]

问题描述 投票:0回答:2

我正在尝试创建一个汽车类,用户可以在其中查看我的C#101类的汽车状态(即查看汽车是否在行驶)。但我只是不能因为我的爱而使它正常工作,并不断出现此错误:

5.cs(43,31):错误CS1503:参数1:无法从'void'转换为'bool'

不允许在Main类中进行更改。

据我所知:

class Car 
{
    bool isDriving = true;

    public void status() {  
        if (isDriving == false) {
            Console.Write("The car is standing still");
        }
        else if (isDriving == true) {
            Console.Write("The car is moving");
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Car ferrari = new Car();
        Console.WriteLine(ferrari.status());
    }
}

希望得到帮助<3

c#
2个回答
1
投票

您的方法status()返回void-没什么。

在主方法中,您试图将“ status”方法的返回值打印到控制台。但是Console.WriteLine(...)不接受空值。

您必须执行此操作:

选项1:可以将您的状态方法更改为:

 public string status() {  
    if (isDriving == false) {
        return "The car is standing still";
    }
    else if (isDriving == true) {
        return "The car is moving";
    }
}

然后返回一个可以打印的字符串,

选项2:将您的主要方法更改为:

static void Main(string[] args)
{
    Car ferrari = new Car();
    ferrari.status();
}

除此之外,重新考虑如何评估isDriving布尔值。我会说,您对if子句的使用不是最佳的。您可以这样做:

if (isDriving == false) {
    return "The car is standing still";
}
else {
    return "The car is moving";
}

或更简洁:

return isDriving ? "The car is moving" : "The car is standing still";


1
投票

您将方法状态声明为无效:

public void status()

因此,意味着此函数不返回任何内容。然后使用此函数作为参数:

Console.WriteLine(ferrari.status());

这不是必需的,因为status()本身会打印一些内容,所以您可能只想在此之后添加换行符。

所以,应该足够了:

static void Main(string[] args)
{
    Car ferrari = new Car();
    ferrari.status();
    Console.WriteLine(); // new line only
}
© www.soinside.com 2019 - 2024. All rights reserved.