在C#中可以将不同类型的接口保存到一个变量中吗?

时间:2017-06-11 03:52:51

标签: c#

假设我有界面:

public interface ISlot<TType>
{
    TType Slot { get; }
}

然后有两个类实现它:

public class DungeonInventorySlot : ISlot<DungeonInventorySlot>
{
    DungeonInventorySlot ISlot<DungeonInventorySlot>.Slot 
    {
        get { return this; } 
    }
}

public class ActiveSkillSlot : ISlot<ActiveSkillSlot>
{
    ActiveSkillSlot ISlot<ActiveSkillSlot>.Slot 
    {
        get { return this; } 
    }
}

现在在控制器类上我希望有一个变量在任何给定时间保持其中一个(将来可能会超过2个):

public class BattleFlow
{
    private ISlot<> HoldSlot;
}

这在C#中是否可行?什么是这个问题的好方法?

目前,每种类型都有几个变量,但在任何给定时间只设置一个。

1 个答案:

答案 0 :(得分:0)

使用一些基类并使ISlot模板参数与out接口:

    public interface ISlot<out TType>
    {
        TType Slot { get; }
    }

    public class BaseClass
    {
    }

    public class DungeonInventorySlot : BaseClass, ISlot<DungeonInventorySlot>
    {
        DungeonInventorySlot ISlot<DungeonInventorySlot>.Slot
        {
            get { return this; }
        }
    }

    public class ActiveSkillSlot : BaseClass, ISlot<ActiveSkillSlot>
    {
        ActiveSkillSlot ISlot<ActiveSkillSlot>.Slot
        {
            get { return this; }
        }
    }

    public class BattleFlow
    {
        public ISlot<BaseClass> HoldSlot;
    }

    private void Test()
    {
        var s = new BattleFlow();
        s.HoldSlot = new ActiveSkillSlot();
        s.HoldSlot = new DungeonInventorySlot();
    }