如何解决此错误“错误CS1503:参数1:无法从'无效'转换为'布尔'”

时间:2019-12-07 17:23:13

标签: c#

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

5.cs(43,31):错误CS1503:参数1:无法从“无效”转换为“布尔”

不允许在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

2 个答案:

答案 0 :(得分:2)

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

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

您必须这样做:

选项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 :(得分:1)

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

    /** @var \Illuminate\Database\Eloquent\Factory $factory */
    use App\User;
    use Illuminate\Support\Str;
    use Faker\Generator as Faker;



    $factory->define(User::class, function (Faker $faker) {
        return [
            'name' => $faker->name,
            'phone' => $faker->phoneNumber,
            'profile_image' =>'http://via.placeholder.com/150x150',
            'email' => $faker->unique()->safeEmail,
            'email_verified_at' => now(),
            'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
            'remember_token' => Str::random(10),
        ];
    });

    $factory->define(Message::class, function (Faker $faker) {
      do{
        $from = rand(1, 15);
        $to = rand(1, 15);
      } while ($from == $to);


        return [
            'from' => $from,
            'to' => $to,
            'text' => $faker->sentence,

        ];
    });

因此它意味着此函数不返回任何内容。 然后,您可以将此函数用作参数:

public void status()

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

所以,这应该足够了:

Console.WriteLine(ferrari.status());