使字段只能访问其对应的属性?

Joh*_*ohn 2 .net c#

假设我们有一个私人支持字段和一个公开该字段的私有财产。如果任何代码(甚至类中的代码)尝试访问或修改除属性以外的字段,而没有将字段和属性封装在自己的对象中,则C#是否支持属性或任何其他语法来强制编译器错误?请在下面看到一个简单的例子。

/// <summary>
/// Class to cache and quickly access data. Please only use this class if 1) the data to be cached  uses little memory and 2) the number of DB reads is high and could cause a performance strain.
/// </summary> 
class BMIDataCache
{
    #region fields
        protected static BMITimedDictionary<String, Device> _devices;
    #endregion

    #region properties
    protected static BMITimedDictionary<String, Device> Devices
    {
        get
        {
            if (_devices == null)
            { 
                _devices = new BMITimedDictionary<String, Device>();
                //Do some other stuff later.
            }
            return _devices;
        }
        set
        {
            _devices = value;
        }
    }
public void Test1()
{ //Inside this method, trying to access _devices will cause a compiler error, but not Devices
}
}
Run Code Online (Sandbox Code Playgroud)

Ale*_*kov 5

C#中没有什么可以帮助您private向同一类的成员隐藏字段。

您的选择:

  • 一些后期处理(即,使用FxCop进行代码分析的自定义插件)
  • 将此字段/属性移至基类并标记字段 private。比将真实代码添加到派生类-这样派生类将无法访问字段
  • 而是使用包含接口的容器。

旁注:您将无法隐藏反射区域...