WriteLine method C#

本文关键字:method WriteLine | 更新日期: 2023-09-27 18:11:28

我试图使一个程序,您输入一个int值,然后使用方法从该整数中添加或减去数字"10"。问题是,当我写:Console.WriteLine("After addition, your value is now {0}",CustomClass.CustomClass'Method);编译器告诉我不能将对象转换为方法。下面是我的代码:

public class CarClass
{
    public static string carModel;
    public static int carSpeed;

    public static void Accelerate()
    {
        carSpeed = carSpeed + 10;
    }
public static void Brake()
    {
        carSpeed = carSpeed - 10;
    }


}
class MainClass
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Enter car model: ");
        CarClass.carModel = Console.ReadLine();
        Console.WriteLine("Enter initial speed: ");
        CarClass.carSpeed = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine("Starting speed of {0} is {1} km/h.", CarClass.carModel, CarClass.carSpeed);
        Console.WriteLine("Now some speed changing...");

Console.WriteLine("After accelerating, new speed of {0} is {1} km/h.",CarClass.carModel,CarClass.carSpeed + CarClass.Accelerate); // here the speed should be starting speed + 10
Console.WriteLine("After accelerating, new speed of {0} is {1} km/h.",CarClass.carModel,CarClass.carSpeed + CarClass.Accelerate); //here the speed should be the previous speed + 10

        Console.ReadLine();
    }
}
}

我不确定这是否是使加速度的正确方法,因为我需要它来存储以前的值,然后再次添加"10"。如果你们能帮我解决这个问题,我会非常感谢你们的。

WriteLine method C#

你的问题是这个表达式:

CarClass.carSpeed + CarClass.Accelerate

carSpeed为整数,Accelerate为方法。你不能把数字和方法加在一起,这没有任何意义。

您要做的是执行方法,这将更新carSpeed。然后可以打印carSpeed的值。比如:

CarClass.Accelerate();
Console.WriteLine("After accelerating, new speed of {0} is {1} km/h.", 
    CarClass.carModel, CarClass.carSpeed);