加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 强制使用接口而不是声明中的具体实现(.NET)

发布时间:2020-12-15 18:23:35 所属栏目:百科 来源:网络整理
导读:在C中,您可以执行以下操作: 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()
在C中,您可以执行以下操作:
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()并将其设为私有.结果是,调用此方法的唯一方法是这样的:

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

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

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

我认为这很好,因为如果你创建一个用作接口的抽象类,你可以确保没有人意外地声明一个字段作为具体类型,但总是使用接口类.

因为在C#/ .NET中,一般情况下,在覆盖方法时,不允许缩小从公共到私有的访问权限,有没有办法在这里实现类似的效果?

解决方法

如果您明确实现了一个接口,这至少会鼓励人们在声明中使用接口类型.
interface IMyInterface
{
    void MyMethod();
}

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

在将实例强制转换为IMyInterface之后,只能看到MyMethod.如果声明使用接口类型,则后续使用中不需要转换.

MSDN page on explicit interface implementation(谢谢卢克,救我几秒钟^^)

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读