了解私人setter方法 [英] understanding private setters

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

问题描述

我不明白它开始用C#有私家制定者需要2

I don't understand the need of having private setters which started with C# 2.

有一个setter方法​​对我来说让用户设置一些变量的类。在这样做,我们不会直接暴露变量给用户。相反,我们让他们做到这一点通过这个公共的setter方法​​。

Having a setter method for me is letting the user to set some variables in that class. In doing so, we will not expose the variables directly to the users. Instead we let them do it through this public setter method.

这对我来说是使用封装。有一些争论在那里它声称私有制定者将让你应用的封装。

This for me is using "encapsulation". There are some arguments out there which claim that private setters will let you apply encapsulation.

我是不是不使用封装使用公共setter方法​​?我们为什么需要私人setter方法​​?

Am I not using encapsulation by using public setter methods? Why do we need private setters?

什么是不可变类和带私人setter方法​​的类之间的区别?

What is the difference between immutable class and a class with private setters?

推荐答案

按道理。

私人二传手的presence是因为你可以使用自动属性:

The presence of a private setter is because you can use auto property:

public int MyProperty { get; set; }

如果你想让它只读你会怎么做?

What would you do if you want to make it readonly?

public int MyProperty { get; }

呵呵废话!我无法从我自己的类进行访问;我应该像一个正常的属性创建它:

Oh crap!! I can't access it from my own class; I should create it like a normal property:

private int myProperty;
public int MyProperty { get { return myProperty; } }

嗯......但我失去了自动属性的功能...

Hmm... but I lost the "Auto Property" feature...

public int MyProperty { get; private set; }

AHHH ..这是更好!

AHHH.. that is better!!

这篇关于了解私人setter方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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