如何在实现接口的每个对象上设置属性的默认值?

Fra*_*kie 2 c# oop interface

我的IVehicle接口上有一个名为Color的属性.如果我希望每个实现该界面的车辆都具有默认颜色"红色",我怎么能实现这一目标?我需要另一个级别吗?

public interface IVehicle
{
    string Color { get; set; }

    void Go();        
    void Stop();
}

public class Bmw : IVehicle
{

    #region IVehicle Members

    public string Color
    {
        get
        {
            throw new NotImplementedException();
        }
        set
        {
            throw new NotImplementedException();
        }
    }

    public void Go()
    {

    }

    public void Stop()
    {

    }

    #endregion
}
Run Code Online (Sandbox Code Playgroud)

Ree*_*sey 8

如果我希望从该界面继承的每辆车都具有默认颜色"红色",我怎么能实现这一目标?

这实际上是一个实现细节,因此它不是界面的一部分.接口无法决定类如何实现它 - 只需要实现成员.

如果您想要这种类型的控件,您可能希望使用abstract class而不是接口.一个Vehicle基类可以设置使用默认的实现Colors.Red.