子类对象使用(或尝试使用)父类对象函数而不是它自己的函数

问题描述 投票:0回答:1

开门见山,在 WinForms 项目中,我有以下类(全部位于同一命名空间中):

private class Operation
{
    //Empty because it's simply base class
    //A "ToStrings" is planned though
}

private class Enumer : Operation
{
    //"index" field not needed
    private String? tmpl;
    private int start;
    private int digits;
    private int step;

    public Enumer(String tmpl_, int start_, int digits_, int step_)
    {
        tmpl = tmpl_;
        start = start_;
        digits = digits_;
        step = step_;
    }

    public Enumer(Dictionary<string, object> j)
    {
        tmpl = (string)j["riTabsOpsTabsEnmTmpFld"];
        start = Decimal.ToInt32((decimal)j["riTabsOpsTabsEnmOptsStrtFld"]);
        step = Decimal.ToInt32((decimal)j["riTabsOpsTabsEnmOptsStepFld"]);
    }

    public new void ExecuteOpp(FileLst wrkngLst)
    {
        //Contents not relevant to problem.
    }
}

Enumer
类是使用以下
Dictionary
对象和函数创建的:

private static Dictionary<string, Func<Dictionary<string, object>, Operation>> operationsDict = new Dictionary<string, Func<Dictionary<string, object>, Operation>>
{
    {"enum", (dic) => new Enumer(dic)}, 
    //{"class2", (dic) => new Class2(dic)}
};
public void executeOpp(Dictionary<string, object> opDic)
{
    Operation op = operationsDict[(string)opDic["op"]](opDic);
    op.ExecuteOpp(bigLst); //<---
}

我在这里尝试做的是根据我的

Dictionary
对象中的匹配项动态创建一个类,然后执行其函数。最终计划是拥有
List<T>
Operations

问题发生在 <---), is. From what I am getting from the debugger, the

ExecuteOpp()
中的 (
Operation
函数成为目标,而不是
Enumer
中的函数。

以下是调试器对

op
对象的描述(已使用所有拍米数成功构建):

名字 价值 类型
op {rename_inator2.Functionals.Enumer} rename_inator2.Functionals.Operation {rename_inator2.Functionals.Enumer}

对于我的尝试,我没什么可说的。我最初将责任归咎于我自己的“动态类工厂”实现,并寻找其他实现来尝试。就像这个这个。但每一个都导致了同样的问题。

我应该注意到,如果我这样做,代码确实可以工作,

Enumer e1 = new(opDic);
e1.ExecuteOpp(bigLst); 

解决方案可能就在我面前晃来晃去,但我可能只是不知道要搜索什么术语。我也愿意尝试一种新的方法来实现我的总体计划。如有任何帮助,我们将不胜感激。

c# winforms class
1个回答
0
投票

如果没有

overriding
,你只是隐藏了基类中声明的方法,因此,基类的变量(指向子类)将导致基类的方法执行。尝试使用
virtual
/
overriding

© www.soinside.com 2019 - 2024. All rights reserved.