这是一个选项 – 不使用枚举,但类似的东西 – 是…
public abstract class Logic
{
public static readonly Logic PayDay = new PayDayImpl();
public static readonly Logic CollectCash = new CollectCashImpl();
public static readonly Logic EtcEtc = new EtcEtcImpl();
// Prevent other classes from subclassing
private Logic() {}
public abstract void AcceptPlayer(Player player);
private class PayDayImpl : Logic
{
public override void AcceptPlayer(Player player)
{
// Perform logic
}
}
private class CollectCashImpl : Logic
{
public override void AcceptPlayer(Player player)
{
// Perform logic
}
}
private class EtcEtcImpl : Logic
{
public override void AcceptPlayer(Player player)
{
// Perform logic
}
}
}
你说你不想为每一个逻辑提供一个具体的类 – 但这基本上就是你用Java做的事情,只是这个类会稍微隐藏你.
以下是使用委托处理不同行为的替代方法:
public sealed class Logic
{
public static readonly Logic PayDay = new Logic(PayDayAccept);
public static readonly Logic CollectCash = new Logic(CollectCashAccept);
public static readonly Logic EtcEtc = new Logic(player => {
// An alternative using lambdas...
});
private readonly Action accept;
private Logic(Action accept)
{
this.accept = accept;
}
public void AcceptPlayer(Player player)
{
accept(player);
}
private static void PayDayAccept(Player player)
{
// Logic here
}
private static void CollectCashAccept(Player player)
{
// Logic here
}
}
在这两种情况下,您仍然可以获得一组固定的值 – 但您将无法打开它们.你可能有一个单独的“真实”枚举,但这会有点混乱.