如何来实行的方法,因为接口方法仅公开? [英] How to enforce private method since interface methods are only public?

查看:99
本文介绍了如何来实行的方法,因为接口方法仅公开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

接口,可用于强制方法的实现,但他们需要的是公众。

Interface can be used to force methods implementations but they need to be public.

如果我要强制执行的私有方法又是什么?

What if I want to enforce private methods then ?

更新:这不是preventing调用,它是关于确保私有方法已经实施

Update: It's not about preventing to call, it's about ensuring that the private method has been IMPLEMENTED.

所以我不想使用的界面本身。我想强加编码到一个团队的一些风格。

So I don't want to use interface per se. I want to impose some style of coding to a team.

推荐答案

接口总是被定义公众。只有这样,才能执行保护(专用于外部,而是访问派生类)方法的实现是通过继承,它定义了一个抽象类方法:

Interfaces are always by definition public. The only way to enforce the implementation of a protected (private to the outside but accessible to derived classes) method is by subclassing an abstract class that defines that method:

public abstract class A
{
    protected abstract void Foo();
}

public class B : A
{
    protected override void Foo() { }
}

以上将打破,如果你想改变的访问修饰符在 B ,或忘记为提供实现美孚() B

The above will break if you are trying to change Foo's access modifier in B, or forget to provide an implementation for Foo() in B.

编辑:

我相信实现的东西的代码应用于使用的嵌套类,这只是可见的课外:这将允许使用外部类的,并在同一时间执行一个接口的实现的私有字段,而技术上类不是可见于其他地方:

I believe achieving something close to what you want is possible using a nested class that is only visible to the outside class: This would allow using the private fields of the outer class and at the same time enforcing the implementation of an interface while technically the class is not visible from anywhere else:

public interface IFooWorker
{
    void DoWork();
    int CalculateSomething();
}

public class Foo
{
    private FooWorker _worker;
    private int _currentValue;
    private string _workStatement;


    public Foo()
    {
        _worker = new FooWorker(this);
    }

    private class FooWorker : IFooWorker
    {
        private Foo _outer;
        public FooWorker(Foo foo)
        {
            _outer = foo;
        }

        public void DoWork()
        {
            _outer._currentValue = CalculateSomething();
            _outer._workStatement = "I did work";
        }

        public int CalculateSomething()
        {
            return 42;
        }
    }

}

这篇关于如何来实行的方法,因为接口方法仅公开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆