受保护的只读字段与受保护的属性 [英] Protected readonly field vs protected property

查看:108
本文介绍了受保护的只读字段与受保护的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个抽象类,我想在其受保护的构造函数中初始化一个只读字段.我希望此只读字段在派生类中可用.

I have an abstract class and I'd like to initialize a readonly field in its protected constructor. I'd like this readonly field to be available in derived classes.

按照我习惯于将所有字段设为私有并公开属性,我实现了以下操作:

Following my habit of making all fields private and exposing properties, I implemented this as follows:

abstract class Foo
{
    private readonly int _field;

    protected Foo(int field)
    {
        _field = field;
    }

    protected int Field
    {
        get { return _field; }
    }
}

但是后来我想知道在这里保持私有字段是否真的有很多优势.我知道属性的优点,并且在这个问题上总体上存在一些SO问题,但它们关注的是公共领域,而不是受保护的领域.

But then I wondered if there is really much advantage of keeping the field private here. I'm aware of the advantages of properties and there are several SO questions on this issue in general, but they focus on public fields as opposed to protected ones.

那么我是否应该切换到以下实施方式? 在这两种情况下都应注意哪些注意事项和优点/缺点?

So should I switch to the below implementation or not? What are the considerations and advantages/disadvantages to be aware of in either case?

abstract class Foo
{
    protected readonly int _field;

    protected Foo(int field)
    {
        _field = field;
    }
}

推荐答案

派生类仍然是原始代码的用户";字段也应该从它们中封装出来.

Derived classes are still 'users' of the original code; fields should be encapsulated from them too.

您应该将基类视为安全且可扩展的API,而不仅仅是暴露其内部的类.保持字段私有-除了任何其他内容,它允许基类更改属性值的生成方式:)

You should think of base classes as safe and extendable APIs, rather than just classes which expose their internals. Keep the fields private - apart from anything, it allows the base class to change how that property's value is generated :)

这篇关于受保护的只读字段与受保护的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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