在哪里定义常量并在任何地方使用它们?

Kap*_*ino 3 c# oop interface

在Java中我会写类似的东西

public interface ICar {    
    static String RED_CAR = "/res/vehicles/car_red.png";
    static String BLUE_CAR = "/res/vehicles/car_blue.png";
    static String GREEN_CAR = "/res/vehicles/car_green.png";    
}
Run Code Online (Sandbox Code Playgroud)

因为C#不允许在接口中使用字段,所以当我想在C#中定义这些常量时,我​​希望多次使用它们?

Vse*_*nin 11

您可以定义一个静态类来包含您的常量(public默认情况下需要不带修饰符的字段private):

public static class Car
{
    public const string RED_CAR = "/res/vehicles/car_red.png";
    public const string BLUE_CAR = "/res/vehicles/car_blue.png";
    public const string GREEN_CAR = "/res/vehicles/car_green.png"; 
}
Run Code Online (Sandbox Code Playgroud)

在此之后你可以使用常量Car.RED_CAR.

  • 我不会在名字中使用`_`而不使用BLOCK字母.记住这是C#而不是C++,也可能将类重命名为`CarLocation`或类似的东西. (2认同)