我正在尝试将随机座位代码链接到我的用户界面类,我很难理解如何通过我的用户界面随时调用它。以下内容目前保留在 {
Random rand = new Random();
bool[] seats = new bool[32];
//To keep a separate list of seats taken
List<int> seatsBooked = new List<int>();
bool quit = false;
do
{
Console.Clear();
//int seatAssignFirstClass = rand.Next(0, 32);-> Moved to switch-case 1: block
int seatAssignThirdClass = rand.Next(32);
int seatAssignFirstClass; //Variable moved from main loop
//Are there any seats booked already or this is the first?
if (seatsBooked.Count == 0) //if this is the first seat to be booked...
{
seatAssignFirstClass = rand.Next(0, 32);
seats[seatAssignFirstClass] = true;
seatsBooked.Add(seatAssignFirstClass); //Add seat to the list of booked seats.
}
else
{
do //while there are available seats and current seat has not being assigned before.
{
seatAssignFirstClass = rand.Next(0, 32);
if (!seatsBooked.Contains(seatAssignFirstClass)) //if seatAssignFirstClass is not booked.
{
seats[seatAssignFirstClass] = true;
}
//repeat while the random seat number is already booked and there are avaialable seats
} while (seatsBooked.Contains(seatAssignFirstClass) && seatsBooked.Count < 32);
//IMPORTANT: Number on line bellow needs tos be one bigger than rest
if (seatsBooked.Count < 34) //if seatsBooked list is not full for First Class
{
seatsBooked.Add(seatAssignFirstClass); //Add current random-generated seat to the list.
}
}
//IMPORTANT: Number on line bellow needs tos be one bigger than rest
if (seatsBooked.Count >= 34) //If all seats are booked
{
Console.WriteLine("All seats for First Class are booked");
Console.WriteLine("Press enter to continue...");
}
else //Give customer their seat nmumber
{
Console.WriteLine("Train seat number: {0}", seatAssignFirstClass + 1);
Console.WriteLine("Press enter to continue to the main menu...");
}
} while (!quit);
级别内。
Toplevel
答案 0 :(得分:2)
C#中最小的代码重用单元是一个函数。您需要将此代码放在一个函数中,然后您可以从其他地方调用它。最容易成为public static
函数,但随着您对设计的了解越多,您可能会发现有更好的方法来共享功能。
答案 1 :(得分:1)
您可以使用using
关键字和所需的类&#39;添加对其他文件中的类的引用。 namespace
示例:
namespace MyProject.MyCore {
public class MyClass {
public void MyMethod() { }
}
}
然后,您将在调用类中引用此命名空间,如下所示:
using MyProject.MyCore
允许您实例化类对象,如下所示:
var myInstantiatedClass = new MyClass();
并称之为:
myInstantiatedClass.MyMethod();
方法也可以标记为静态,这样就无需实例化类,而是使用Type.Method()语法调用,例如MyClass.MyMethod()
。
您还可以使用完全限定的路径放弃添加引用。
var myInstantiatedClass = new MyProject.MyCore.MyClass()
当然,如果此代码位于不同的项目或程序集中,您必须添加对项目或二进制文件的引用以访问它提供的类型。
答案 2 :(得分:0)
This example may be your answer
或者你可以使用像
这样的静态方法np.asarray([np.asarray(a[0]), np.asarray(a[1])]) / 10.
你可以从另一个类
中使用这个方法namespace MyProject.MyCore {
public class MyClass {
public static void MyMethod() { }
}
}