实施后密封接口 [英] Sealing an interface after implementing it

查看:92
本文介绍了实施后密封接口的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我工作的一个小项目,我跨过问题来了。

I am working on a small project and I came across that problem.

项目的产出是包含一个接口库。我想实现该接口并封住它的职能是这样,如果可能的:

The project output is a library containing an interface. I would like to implement that interface and seal the functions in it like this if possible:

public interface ITest
{
    void SomeMethod();
}

class A : ITest
{
    public sealed override SomeMethod()
    {

    }
}

的想法是有提供给大家界面和具有实现它的一些专门的类。唯一的例外是,我要确保,如果有人专门创建类A型的,他/她将无法改变方法的行为。

The idea is to have the interface available to everyone and have some specialized class that implements it. The exception is that I want to make sure that if someone create a specialized class of type A, he/she won't be able to change the method's behavior.

问题是你不能把覆盖关键字在那里,因为该方法不作为界面中的虚拟的声明。并且由于它是不允许你不能将其声明为在接口虚拟。而且,由于它是由封闭需要你不能删除覆盖的关键字。

The problem is you can't put the "override" keyword in there since the method isn't declared as "virtual" in the interface. And you can't declare it as "virtual" in the interface since it's not allowed. And you can't remove the "override" keyword since it's needed by "sealed".

任何解决办法或脑力激荡的想法是值得欢迎的,但如果有人能想出包括接口的解决方案,我会非常高兴地获悉了!

Any workaround or brainstorming idea would be welcome, but if someone can come up with a solution that includes an interface, I'd be really happy to learn it!

谢谢!

编辑:忘记了这个问题!像阿尼说,我忘了,在C#中默认的方法是密封的。好像总是好的回去的基本知识过一段时间......

Forget this question! Like Ani said, I forgot that by default method in C# are sealed. Seems like it's always good to go back to the basics once in a while...

推荐答案

我可能完全误解了这个问题,但如果你的目的是要封住 A 的方法,你可以这样做:

I may have completely misunderstood the question, but if your intention is to seal the method in A, you can just do:

class A : ITest
{
    public void SomeMethod()  { ... }
}

与Java,C#中的方法是密封的默认的。的子类 A 将无法覆盖的方法,因为它没有被标记虚拟

Unlike Java, methods in C# are sealed by default. Subclasses of A won't be able to override the method since it hasn't been marked virtual.

在另一方面,如果你的目的是纪念在界面几乎密​​封的方法,所以,它的力量的在实现类立即其密封,这是不可能的。它不是(且不应)的接口的业务来规定执行这样的细节 - 接口是代表一个的规范

On the other hand, if your intention is to mark the method 'almost sealed' in the interface, so that it forces upon an implementing class to immediately seal it, that isn't possible. It isn't (and shouldn't be) the business of the interface to dictate such details of implementation - an interface is meant to represent a specification.

这篇关于实施后密封接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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