私人设置或私有成员? [英] Private Set or Private member?

查看:115
本文介绍了私人设置或私有成员?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道什么被认为是C#最佳实践,私有/ protected成员公共干将,或与私人/保护的setter方法​​公开getter方法​​?

I was wondering what's considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?

       public int PublicGetPrivateSetter
       {
            get;
            private set;
        }







        private int _privateMember;

        public int PublicGetPrivateMember
        {
            get { return _privateMember; }
        }



我觉得用一个私有成员更加明确在你的代码,它的私人二传手(使用命名约定)。
在使用私有制定者另一方面使您能够使用一个选择虚拟(保护),写更少的代码,有犯错的余地更小,可以给你一个选择以后,如果你需要添加一个副作用。

I feel that using a private member is more explicit in your code that it's a private setter (using naming conventions). On the other hand using private setters gives you an option to use virtual (protected), write less code, has less room for mistakes and can give you an option to add a side effect later on if you need to.

我找不到什么最好的做法,或者即使一个被认为是优于其他。从我所看到的时间通常80%(从我见过的代码)人们不使用专用的制定者......我不知道这是否是因为人们不知道的私人制定者,还是因为它的,认为是更好的实际使用私有成员

I couldn't find what's considered a best practice, or even if one is considered better than the other. From what I've seen usually 80% of the time (from code that I'VE seen) people DONT use private setters... I'm not sure if this is because people don't know about private setters, or because it's considered better to actually use private members.

编辑:

事实上,这是我用的时候忘了其他的好处私有成员是默认值,并使用只读。

Indeed, other benefits which I forgot about when using private members is default values and the use of readonly.

推荐答案

我更喜欢使用自动实现的属性,除非默认的实现没有按'做T我想要的。因此,在这种情况下,由于自动实现的属性确实你需要什么,只需使用:

I prefer to use auto-implemented properties unless the default implementation doesn't do what I want. So in this case, since the auto-implemented property does what you need, just use that:

public int Foo { get; private set; }



但是另一种情况是,如果你想现场只读(即所在的字段可以设置的唯一地方是在构造函数)。然后,你需要定义支持字段和只读标记为这不是由自动实现属性的支持:

However another situation is if you want to make the field readonly (meaning that the only place where the field can be set is in the constructor). Then you need to define the backing field and mark it readonly as this isn't supported by auto-implemented properties:

private readonly int foo;

public int Foo
{
    get { return foo; }
}

这篇关于私人设置或私有成员?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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