揭露保护领域的最佳方法 [英] Best way to expose protected fields

查看:179
本文介绍了揭露保护领域的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个基类是这样的:

I have a base class like this:

 public class BaseModalCommand
 {

    protected object m_commandArgument;
    protected int m_commandID;
    protected int m_enableUIFlags;

    public virtual void OnIdle()
    {
    }

    public virtual void OnResume()
    {
    }

    public virtual void OnStart(int commandID, object argument)
    {
    }

    public virtual void OnStop()
    {
    }



    public virtual int EnableUIFlags
    {
        get
        {
            return this.m_enableUIFlags;
        }
    }
}



虚拟方法是覆盖在派生类型。如果我运行它直通的FxCop,它抱怨不声明可见实例字段,并建议其更改为私人和揭露它作为一个受保护的属性。

The virtual methods are to be overridden in derived types. If I run it thru FxCop, it complains about not declaring visible instance fields and recommends changing it to private and exposing it as a protected property.

有什么想法? 。我想这个消息可以被忽略

Any thoughts? I'm thinking this message can be ignored.

推荐答案

有关的任​​何类,也有通过客户端代码的两个类型使用:代码引用类和代码继承类。它的广泛承认,第二类使用的是迄今为止最紧密耦合。在你的类的变化直接影响到他们的内部机制。这样你揭保护成员意味着在你的基类的变化将影响到你的派生类中说,是没有比较每个基类和派生类的代码不可预知的方式是如何工作的。同样糟糕,你的派生类可以修改基类的内部结构。

For any class, there are two kinds of uses by client code: code that references your class, and code that inherits your class. It's widely recognized that the second kind of use by far the most tightly coupled. Changes in your class directly affect their internal mechanics. Your exposing protected members like this means that changes in your base class will affect how your derived classes work in ways that are unpredictable without comparing the code of each base and derived class. Equally bad, your derived classes can modify the internals of the base class.

如果你真的想公开内部数据成员像这样,在保护性包装私有数据成员(作为gisresearch建议)。这些特性(与任何受保护的方法一起)构成了你的类的继承接口。就像暴露在外部客户任何接口(无论是通过定义只,或通过显式接口实现公共方法和属性),该接口是你将需要管理,特别是在较大的代码库。接口是可以改变的,但应改变一个明智的决定。

If you really want to expose internal data members like this, wrap private data members in protected properties (as gisresearch suggests). These properties (along with any protected methods) constitute the inheritance interface of your class. Like any interface exposed to outside clients (whether through just defining public methods and properties, or through explicit interface implementation), this interface is something you will need to manage, particularly in larger code bases. An interface can be changed, but should be changed as a conscious decision.

如果您与受保护的数据成员直接工作,你必须在基类和派生类之间的依赖要少得多的控制。相信我:即使不能够确定什么样的影响的变化可能有可以是一个非常不愉快的事情。

If you work with protected data members directly, you have much less control over the dependencies between base and derived classes. Trust me on this: not even being able to determine what effects a change may have can be a Very Unpleasant Thing.

这篇关于揭露保护领域的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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