将派生 class 显式转换为基础 class

Explicit cast of derived class to base class

我正在尝试将派生的 class 对象转换为其基数 class(通过 JSON 转换保存它)。每当我尝试从派生 class 对象获取基础 class 时,它 returns 是派生 class 的对象。我无法获得基础 class 对象(尝试使用显式和隐式强制转换以及转换)。

public class PlanningListModel : INotifyPropertyChanged
{
    private DateTime _date;
    private List<PlanningEntryModel> _Plannings;
    private bool _isSaving = false;

    public List<PlanningEntryModel> Plannings {get=>_Plannings;} //field i want to serialize
    //Same declarations for public fields
}

public class PlanningListViewModel :PlanningListModel   INotifyPropertyChanged
{
    private DateTime _date;
    private List<PlanningEntryModel> _Plannings;
    private bool _isSaving = false;

    public List<PlanningEntryModel> Plannings{           
        get {
            if (App.Data == null || App.Data.User == null || App.Data.IsReplicating)
                return base.Plannings.FindAll(x => true);
            switch (App.Data.CurrentList) {
                case 0: return base.Plannings.FindAll(x => true);
                case 1: return base.Plannings.FindAll(x => x.Volonter.ID == App.Data.User.ID);
                case 2: return base.Plannings.FindAll(x =>  x.User.Referent==App.Data.User.ID);
                default: return base.Plannings.FindAll(x => true);
        }
    }
} 

我想做什么:

PlanningListViewModel A = new PlanningListViewModel ();
PlanningListModel B = (PlanningListModel)A;
typeof(B); // B stays PlanningListViewModel and not PlanningListModel

我需要访问基础class的字段Plannings(因为派生class的Plannings字段被修改(覆盖get )).每当我尝试投射时,该对象仍然是一个 PlanningListViewModel 对象,我无法投射到它的基础 class.

我做错了什么?感谢您的帮助!

I need to access the field Plannings of the base class (because the Plannings field of the derived class is modified (overridden get)).

在你的情况下它不起作用,因为 属性 不是虚拟的。您必须这样声明:

public class PlanningListModel : INotifyPropertyChanged
{
    …
    public virtual List<PlanningEntryModel> Plannings {get=>_Plannings;}
}

然后像这样覆盖:

public class PlanningListViewModel : PlanningListModel
{
    …
    public override List<PlanningEntryModel> Plannings { … }
}

然后对 B.Plannigs 的调用将如您预期的那样工作,即调用 PlanningListViewModel class.

中声明的 getter

Whenever I try to cast, the object stays a PlanningListViewModel object, I am unable to cast to its base class.

是的,这是设计使然。下面两行是等价的:

PlanningListModel B = (PlanningListModel)A;
PlanningListModel B = A;

你看,甚至不需要显式转换。 cast不会改变对象的类型(为了完整性:在一个相当罕见的自定义重载转换运算符中这不是真的)。它只会影响您查看该对象的方式,即您看到的内容。