简体   繁体   中英

Is there any reason to use very simple properties over fields?

I currently have this code written:

public class General
{
    /// <summary>
    /// Private variables.
    /// </summary>
    private const float fVersion = 1.3f;
    private static bool bMonitoring = false;

    /// <summary>
    /// Retrieves the current version of the application.
    /// </summary>
    public static float Version
    {
        get
        {
            return fVersion;
        }
    }

    /// <summary>
    /// Are we monitoring performance?
    /// </summary>
    public static bool Monitoring
    {
        get
        {
            return bMonitoring;
        }

        set
        {
            bMonitoring = value;
        }
    }
}

In case I check for General.bMonitoring or General.Version often (maybe.. over 100 times a second!) and really care about performance: is it good practice to leave my class written like that, or should I simply delete these properties and make the fields public?

In this case if you aren't going to add some logic to the getter or setter then I would use static fields. Performance will be the same.

But if later you need extra logic when you set ot get values then it preffer to use properties because it allows for versioning and it gives you Encapsulation according to OOP principles. Don't care about performance

For Monitoring property you can use Auto-Implemented Property like

public static bool Monitoring { get; set; }

but in this case you need to implement a static constructor (thanks to @Mafii)

    static General()
    {
        Monitoring  = false;
    }

or if you use C# 6.0 then just:

public static bool Monitoring { get; set; } = false;

Don't worry about performance. Property access is (and should be) very fast and compiler may inline them.

Property is preferred over field not because of performance, but because encapsulation and it will really helps when later you need for example checking or make property computed.

More by Jon Skeet http://csharpindepth.com/Articles/Chapter8/PropertiesMatter.aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM