.net访问类内部的局部变量

时间:2018-10-09 03:34:04

标签: c# .net oop

我是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不是每个类实例的属性。很抱歉,如果我选择了一些术语。

2 个答案:

答案 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;