有没有在C#中使用私有属性的任何原因? [英] Are there any reasons to use private properties in C#?

查看:300
本文介绍了有没有在C#中使用私有属性的任何原因?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚意识到,C#的属性构造也可以使用私人访问修饰符使用:

I just realized that the C# property construct can also be used with a private access modifier:

private string Password { get; set; }

尽管这在技术上是有趣的,我无法想象我会用它,因为一个 private字段涉及即使少仪式

private string _password;

和我会永远需要能够在内部的 GET 的但不是的设置 设置的而不是获得私有字段:

and I can't imagine when I would ever need to be able to internally get but not set or set but not get a private field:

private string Password { get; }

private string Password { set; }

但也许有一个用例的嵌套/继承类或也许是其中的get / set可能包含的逻辑而不是只给回的财产的价值,虽然我会倾向于保持性能严格简单,让明确的方法做任何逻辑,如 GetEn codedPassword()

but perhaps there is a use case with nested / inherited classes or perhaps where a get/set might contain logic instead of just giving back the value of the property, although I would tend to keep properties strictly simple and let explicit methods do any logic, e.g. GetEncodedPassword().

有谁在C#中使用的专用属性以任何理由或只是那些技术上可能-尚未很少使用的功能于actual- code结构之一?

尼斯的答案,通过他们看完宰杀我这些用途为私有属性:

Nice answers, reading through them I culled these uses for private properties:


  • 当私人领域需要被延迟加载

  • 当私人领域需要额外的逻辑或者是计算值

  • 因为私人领域可能很难调试

  • 在以present的合同,自己

  • 要在内部转换/简化暴露的财产作为系列化的一部分

  • 包装全局变量类的内部使用

推荐答案

我使用他们,如果我需要缓存的值,并希望延迟加载它。

I use them if I need to cache a value and want to lazy load it.

private string _password;
private string Password
{
    get
    {
        if (_password == null)
        {
            _password = CallExpensiveOperation();
        }

        return _password;
    }
}

这篇关于有没有在C#中使用私有属性的任何原因?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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