我是C#和.Net框架的新手,正在努力了解如何做某事。我是否需要继承这样的东西?
当变量allDim
为true时,我希望所有类实例为其dimPercent.
返回0
public class Program
{
//if this is true, all rooms should return 0
public bool allDim = false;
public class Room
{
//0 is lights out. 100 is as bright as possible
public Room(int dimPercent)
{
DimPercent = dimPercent;
}
private int dimPercent;
public int DimPercent
{
get
{
if (Program.allDim)
{
//if allDim is true, all lights should be dimmed to 0 percent
return 0;
}
else
{
return dimPercent;
}
}
set
{
dimPercent = value;
}
}
}
public static void Main()
{
Room livingRoom = new Room(80);
Room kitchen = new Room(85);
Room bedroom = new Room(65);
allDim = true;
// This should return 0 since allDim was set to true
Console.WriteLine(kitchen.DimPercent);
}
}
创建一个容纳allDim
的基类并允许从该新基类派生Room类对我来说是不合适的,因为从技术上来说allDim
不是每个类实例的属性。很抱歉,如果我选择了一些术语。
答案 0 :(得分:2)
如果将allDim
设为私有静态字段,则可以轻松实现所需的目标。但是,从责任的角度出发,您应该问自己一个房间实例是否应该能够影响其他房间?
public class Room
{
private static bool allDim = false;
// I am not sure if we should make this into a static method
public void SetAllDim(bool isAllDim){
allDim = isAllDim;
}
...
}
答案 1 :(得分:1)
将布尔值转换为该类的静态成员。
public static bool allDim = false;