强制使用接口而不是具体实现的声明(.NET) [英] Force the use of interface instead of concrete implementation in declaration (.NET)

查看:110
本文介绍了强制使用接口而不是具体实现的声明(.NET)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C ++中,您可以执行以下操作:

In C++, you can do the following:

class base_class
{
public:
    virtual void do_something() = 0;
};

class derived_class : public base_class
{
private:
    virtual void do_something()
    {
        std::cout << "do_something() called";
    }
};

derived_class 覆盖方法 do_something()并使其私人。效果是,调用此方法的唯一方法是这样的:

The derived_class overrides the method do_something() and makes it private. The effect is, that the only way to call this method is like this:

base_class *object = new derived_class();
object->do_something();

如果您声明对象类型 derived_class ,你不能调用该方法,因为它是私有的:

If you declare the object as of type derived_class, you can't call the method because it's private:

derived_class *object = new derived_class();
object->do_something(); 
// --> error C2248: '::derived_class::do_something' : cannot access private member declared in class '::derived_class'  

我觉得这是相当不错的,因为如果你创建作为一个接口一个抽象类,你可以确保没有人意外地声明一个字段作为具体类型,但总是使用接口类。

I think this is quite nice, because if you create an abstract class that is used as an interface, you can make sure that nobody accidentally declares a field as the concrete type, but always uses the interface class.

由于在C#/。NET在一般情况下,你不能缩小到私人公开访问>覆盖的方法时,有没有办法在这里实现类似的效果?

Since in C# / .NET in general, you aren't allowed to narrow the access from public to private when overriding a method, is there a way to achieve a similar effect here?

推荐答案

如果你明确地实现一个接口,这至少会鼓励人们使用的接口类型的声明。

If you explicitly implement an interface, this will at least encourage people to use the interface type in the declaration.

interface IMyInterface
{
    void MyMethod();
}

class MyImplementation : IMyInterface
{
    void IMyInterface.MyMethod()
    {
    }
}

一会只能看到铸件的实例 IMyInterface的之后的MyMethod。如果声明使用的接口类型,也没有必要在以后使用铸造

One will only see MyMethod after casting the instance to IMyInterface. If the declaration uses the interface type, there is no casting needed in subsequent uses.

显式接口实现 MSDN页面(感谢卢克,节省我几秒钟^^)

MSDN page on explicit interface implementation (thanks Luke, saves me a few seconds^^)

IMyInterface instance = new MyImplementation();
instance.MyMethod();

MyImplementation instance2 = new MyImplementation();
instance2.MyMethod();  // Won't compile with an explicit implementation
((IMyInterface)instance2).MyMethod();

这篇关于强制使用接口而不是具体实现的声明(.NET)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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