我的问题如下,我有一个类,我们称它为Theatre
。
这个 Theatre
有一个构造函数,我在其中指定了这个 Theatre
拥有的 Seats
数量。
Show
类有一组 Seats
,每个都有自己的属性,例如 bool Empty
。
所以总结一下代码:
class Theatre
{
public Theatre(int numberOfSeats)
{
this.numberOfSeats = numberOfSeats;
}
}
假设我们在某处将其实例化为 100
。
Theatre myTheatre = new Theatre(100);
对于 Show
类:
class Show
{
List<Seats> listOfSeats = new List<Seats>();
public Show()
{
for (int i = 0; i < 100; i++) // <---- And here is my problem!!
{
//Code to add to list
}
}
}
我的问题是我不知道如何摆脱 100
。
我想要像 myTheatre.NumberOfSeats 这样的东西,但我不太确定它是如何工作的。
我的问题是,我已经在另一个类中实例化了 myTheatre,所以我必须在 Show
中创建一个新剧院,只是为了获得座位数,我会使用类似 composition 和授权,但这显然会违反 ISP。
但即使这样也有问题,因为当我制作新的 Theatre
时,我必须将 100
作为参数,如果要改变的话,我将不得不手动更改它。
所以我的问题是:
- 我是否漏掉了一些明显的东西? (很有可能)
- 您会推荐什么方法?
- 是否有跨类共享变量之类的东西? (不想使用全局这个词,因为我不确定那是我想要的,但它可能)。
作为一个明显的说明,以上不是实际代码,只是为了澄清情况的一种表示。
最佳答案
这就是您解决问题的方式。将 Theatre 作为参数传递给 Show
class Theatre
{
public Theatre(int numberOfSeats)
{
NumberOfSeats = numberOfSeats;
}
public int NumberOfSeats { get; private set; }
}
class Show
{
List<Seats> listOfSeats = new List<Seats>();
public Show(Theatre theatre)
{
for (int i = 0; i < theatre.NumberOfSeats; i++) // <---- And here is my problem!!
{
//Code to add to list
}
}
}
class Program
{
static void Main(string[] args)
{
Theatre myTheatre = new Theatre(100);
Show myShow = new Show(myTheatre);
}
}
关于c# - 如何在不实例化两次的情况下跨类共享值(或从另一个类获取变量)。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8074553/