简体   繁体   English

强制执行显式接口

[英]force explicit interface implementation

Imagine we have an interface IFoo : 假设我们有一个接口IFoo

interface IFoo {
    void DoSomething();
}

Now we have an implementing class which calls this method within its constructor: 现在我们有了一个实现类,该实现类在其构造函数中调用此方法:

class MyBase : IFoo {

    MyBase() { this.DoSomething(); }

    void DoSomething() { /* ... */ }
}

Finally we have a class that inherits MyBase but shell provide another implementaion of the interface IFoo . 最后,我们有一个继承MyBase的类,但shell提供了接口IFoo另一种实现。 But when debugging I realise that constructor only accesses the implemetation on MyBase which I understand. 但是在调试时,我意识到构造函数只能访问我了解的MyBase上的实现。 Do get the right implementation of the interface I could explicitly call the interface-method from within the constructor using ((IFoo) this).DoSomething(); 确保正确实现接口,我可以使用((IFoo) this).DoSomething();从构造函数中显式调用接口方法((IFoo) this).DoSomething();

class MyDerived : MyBase, IFoo {
    void DoSomething() { /* ... */ }
}

But how can I enforce that the method MUST be cast to that interface before using it? 但是,我该如何强制该方法在使用之前必须强制转换为该接口? I know I can explicitly implement the interface within both classes, but who forces me to do so? 我知道我可以在两个类中显式实现该接口,但是谁强迫我这样做呢? So we finally come to something like: how can I force someone who inherits my class to explicitly implement my interface also? 因此,我们最终得出这样的结论:我该如何强迫继承我的类的人显式实现我的接口?

EDIT: Another approach would be to make DoSomething virtual in MyBase and ommit the derived class from implementing IFoo . 编辑:另一种方法是在MyBase中使DoSomething虚拟化,并忽略实现IFoo的派生类。 However I get R#-Warning on calling virtual member within constructor then. 但是我得到R#-警告然后在构造函数内调用虚拟成员。

This is what I would do, mark the method in base class as virtual so it can be overriden in the child class. 这就是我要做的,将基类中的方法标记为虚方法,以便可以在子类中将其覆盖。 The child class doesn't need to explicitly implement the interface because it is inheriting the parent's behaviour. 子类不需要显式实现接口,因为它继承了父类的行为。

interface IFoo {
    void DoSomething();
}

class MyBase : IFoo {

    MyBase() { this.DoSomething(); }

    **virtual** void DoSomething() { /* ... */ }
}

class MyDerived : MyBase {
    **override** void DoSomething() { /* ... */ }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM