gpt4 book ai didi

c# - 如何为实现接口(interface)的每个对象设置属性的默认值?

转载 作者:行者123 更新时间:2023-11-30 19:12:14 26 4
gpt4 key购买 nike

我的 IVehicle 接口(interface)上有一个名为 Color 的属性。如果我希望每辆实现该接口(interface)的车辆都具有默认颜色“红色”,我该如何实现?我需要另一个级别吗?

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
}

最佳答案

If I want every vehicle that inherits from that interface to have a default color of "Red" how could I achieve this?

这实际上是一个实现细节,因此它不是接口(interface)的一部分。接口(interface)不能规定类如何实现它 - 只有必须实现哪些成员。

如果您需要这种类型的控件,您可能需要使用抽象类 而不是接口(interface)。 Vehicle 基类可以使用 Colors.Red 设置默认实现。

关于c# - 如何为实现接口(interface)的每个对象设置属性的默认值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8331753/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com