【问题标题】:Overriding a mutator List to change its type of a child覆盖 mutator List 以更改其子项的类型
【发布时间】:2017-02-25 08:15:39
【问题描述】:
public class Schedule_Action : MonoBehaviour
    {
        public List<Action> mondaySchedule = new List<Action>();
        public virtual List<Action> MondaySchedule
        {
            get { return mondaySchedule; }
        }
    }

public class Schedule_ActionHire : Schedule_Action
{
    //causes an error here saying it should match overriden with Action
    public override List<Action_Adventure> MondaySchedule
    {
        get
        {
            return mondaySchedule.Cast<Action_Adventure>().ToList();
        }
    }
}

“Action_Adventure”是“Action”的子级。

有没有办法绕过这个错误?或者可能是与上面给出的代码具有相同逻辑的另一种方式?

【问题讨论】:

    标签: c# unity3d game-engine


    【解决方案1】:

    您无法更改要覆盖的成员的签名。

    但是使用new 可以隐藏基类中的成员:

    public class A
    {
        // no 'virtual' here
        public string Value { get; set; }
    }
    
    public class B : A
    {
        public new int Value { get; set; }
    }
    

    但是这种方法可能会非常令人困惑。

    相反,您可以执行以下操作:从 Action 派生并添加一个抽象方法,以不同方式处理事情:

    public class Action
    {
    }
    
    public class ActionAdventure : Action
    {
    }
    
    public class Base
    {
        private readonly List<Action> _actions = new List<Action>();
    
        public List<Action> Actions
        {
            get { return _actions; }
        }
    
        // call this from your code
        protected virtual void HandleActions()
        {
            foreach (var action in Actions)
            {
            }
        }
    }
    
    public class Derived : Base
    {
        protected override void HandleActions()
        {
            var adventures = Actions.OfType<ActionAdventure>();
            foreach (var adventure in adventures)
            {
            }
        }
    }
    

    【讨论】:

    • 它似乎不起作用。 'var Adventures' 仍然是空的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-16
    • 2013-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多