gpt4 book ai didi

c# - .net 访问类内部的局部变量

转载 作者:行者123 更新时间:2023-11-30 21:31:54 25 4
gpt4 key购买 nike

我是 C# 和 .Net 框架的新手,正在努力了解如何做某事。对于这样的事情,我是否依赖继承?

当变量 allDim 为真时,我希望所有类实例为其 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 在技术上不是一个属性每个类实例。如果我使用了一些术语,我深表歉意。

最佳答案

如果您将 allDim 设为私有(private)静态字段,那么您可以轻松实现您想要的效果。然而,从责任的角度来看,您应该问问自己是否有任何房间实例应该能够影响其他房间?

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;
}
...
}

关于c# - .net 访问类内部的局部变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52712988/

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