我有一个抽象教室,里面有多个孩子班。其中一些孩子拥有财产MaximumCapacity
。当任何东西进入房间时,我希望它检查该房间是否具有该属性,如果有,那么它是什么。我可以使用开关盒轻松地做到这一点,但我不愿意(很多(重复)代码)。
只有两个重要属性:
MaximumCapacity
:房间的最大容量,存储在不同类型房间的一些中CurrentPosition
:存储在要进入房间的对象上的房间。这是我目前拥有的:
// HOW :: Store type of Room in order for me to cast with it.
// My Attempt:
Type T = CurrentPosition.GetType(); // Get the type of the Room
// The following doesn't work:
// Build-time exception: "T is used as a variable but is a type"
if ((CurrentPosition as T).GetProperty("Capacity") != null)
{
// Check capacity and enter Room.
}
我尝试做if (int.Parse(CurrentPosition.GetType().GetProperty("MaximumCapacity")) > [number])
,但这给出了Can't convert type PropertyInfo to Int
。这使我相信我仍然必须将房间抛到高处(我认为)以检查容量。
我该怎么做?
答案 0 :(得分:4)
听起来像interface
和组成的工作。这样,您可以检查您的房间是否支持您的各种功能
给出
public interface IMaximumCapacity
{
int MaximumCapacity { get; set; }
}
public class BaseRoom
{
}
public class DerivedRoom : BaseRoom, IMaximumCapacity
{
public int MaximumCapacity { get; set; }
}
方法
public static bool GetMaximumCapacity(BaseRoom room, out int maximumCapacity)
{
maximumCapacity = 0;
if (room is IMaximumCapacity capcityRoom)
{
maximumCapacity = capcityRoom.MaximumCapacity;
return true;
}
return false;
}
用法
if(GetMaximumCapacity(someRoom,out var max)
{
// yay, do something with max
}
答案 1 :(得分:-1)
您可以执行此操作而无需类型检查。
将MaxCapacity
的类型更改为可为空,并使所有房间都具有此属性。
然后,您可以简单地确定房间是否具有最大容纳量的值
if (room.MaxCapacity.HasValue)
{
// do you logic
}
您可以采用更多面向对象的方式进行操作,将逻辑移至房间对象,以决定是否允许某人进入房间
if (room.AllowedFor(player))
{
// do your logic
}
然后具有MaxCapacity的房间将进行检查,没有MaxCapacity的房间将始终返回false。
答案 2 :(得分:-1)
public abstract class Room
{
public abstract void BookTheRoom();
}
interface IMaximumCapacity
{
int MaximumCapacity { get; set; }
}
public class StorageRoom : Room
{
public override void BookTheRoom()
{
Console.WriteLine("Storage room booked to store the items.");
}
}
public class TwinSharingRoom : Room,IMaximumCapacity
{
public TwinSharingRoom(int capacity)
{
MaximumCapacity = capacity;
}
public int MaximumCapacity { get; set; }
public override void BookTheRoom()
{
Console.WriteLine("Twinsharing room booked.");
}
}
public class SingleSharingRoom : Room, IMaximumCapacity
{
public SingleSharingRoom(int capacity)
{
MaximumCapacity = capacity;
}
public int MaximumCapacity { get; set; }
public override void BookTheRoom()
{
Console.WriteLine("Single sharing room booked.");
}
}
您可以将其用作
class Program
{
static void Main(string[] args)
{
var listOfRooms = new List<Room>() { new SingleSharingRoom(1), new StorageRoom(), new TwinSharingRoom(2) };
foreach(var room in listOfRooms)
{
if(room is IMaximumCapacity)
{
room.BookTheRoom();
}
}
}
}