是否有可能迫使一个接口的实现是在C#中的虚拟? [英] Is it possible to force an interface implementation to be virtual in C#?

查看:79
本文介绍了是否有可能迫使一个接口的实现是在C#中的虚拟?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个问题,今天试图重写它并没有被宣布虚接口方法的实现。

I ran into a problem today trying to override an implementation of an interface method which had not been declared virtual.

在这种情况下,我不能够改变接口或基实现,并有别的尝试一些东西,但我不知道是否有办法迫使一类使用虚拟的方法来实现一个接口。

In this case I'm not able to change the interface or the base implementation and have to try something else, but I was wondering if there was a way to force a class to implement an interface using virtual methods.

interface IBuilder<T>
{
    // Already implicitly virtual
    /*virtual*/ T Build();
}

// This is a class written by someone else
class SimpleBuilder: IBuilder<SomeObject>
{
    // I would like to force this to be virtual
    public SomeObject Build() { return new SomeObject(); }
}

// This is the class I am writing.
class CustomBuilder: SimpleBuilder
{
    public /*override*/ SomeObject Build()
    {
        var obj = base.Build();
        obj.ModifyInSomeWay();
        return obj;
    }
}



编辑: CustomBuilder 旨在与MEF,所以我从 SimpleBuilder 为了导出用于MEF解析正确的类型。我试过明确实现该接口,并从 SimpleBuilder 根本不派生但MEF不拿起正确的类型。

CustomBuilder is intended to be used with MEF so I am deriving from SimpleBuilder in order for MEF to resolve the correct type. I've tried explicitly implementing the interface and not deriving from SimpleBuilder at all but then MEF doesn't pick up the right type.

问题是由其他开发人员创建的,所以它看起来像我将不得不让他们无论如何改变他们的基类共享的模块中。

The interface and base class in question are in a shared module created by another developer so it looks like I will have to get them to change their base class anyway.

推荐答案

没有没有,在你的例子你的含蓄地实现的接口。如果你的类是为了被继承和方法覆盖它是由开发人员,以保证该方法被标记为虚。

No there isn't, in your example you're implicitly implementing the interface. If your class is meant to be subclassed and a method overridden it is up to the developer to ensure that the method is marked as virtual.

有没有办法强制接口方法的实现是在代码覆写投放,只有开发团队中约定可以保证这一点(例如,所有的接口应明确落实,所有。接口实现应标记为虚拟等)

There is no way to force implementations of interface methods to be overrideable in code, only conventions within a development team could ensure this (eg all interfaces should be explicitly implemented, all interface implementations should be marked as virtual etc).

在这个具体的例子,你可以插入一个抽象类成层次结构:

In this specific example you could insert an abstract class into the hierarchy:

abstract class VirtualBuilder<T> : IBuilder<T>
{
  abstract T Build();
}



但是,这并不适用于一般的情况下,因为你失去的有接口利益和力的所有具体类只实现一个接口。

But this isn't suitable in the generic case, since you lose having the benefits of interfaces and 'force' all concrete classes to only implement one interface.

这篇关于是否有可能迫使一个接口的实现是在C#中的虚拟?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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