从父类重写DllImport方法

时间:2018-01-29 15:30:31

标签: c# dll static parent-child

我有一个Parent类,它使用导入函数的.dll

class Parent
{
    [DllImport("example.dll", CallingConvention = CallingConvention.Cdecl)]
    public static extern int dllFunction();
}

现在我想创建一个Child类来测试Parent的功能,而不使用.dll中的方法。我不想使用.dll方法,因为.dll方法与外部传感器通信,我想在没有来自此传感器的输入的情况下测试代码。因此,我需要重新定义.dll方法,以便我可以模拟传感器的行为:

class Child : Parent
{
    public override int dllFunction()
    {

    }
}

目前的Child.dllFunction()方法不起作用,因为我认为Parent.dllFunction()static?是否可以覆盖static类中Parent的{​​{1}}方法?或者您有其他建议吗?

1 个答案:

答案 0 :(得分:4)

我建议这样做:

将PARENT类功能设为私有。创建一个调用它的公共函数,因此不会直接调用它。

[DllImport("example.dll", CallingConvention = CallingConvention.Cdecl)]
private static extern int dllFunction();

public virtual int dllFunctionCaller()
{
    return dllFunction();
}

在你的CHILD课程中,改为覆盖dllFunctionCaller。

相关问题