为什么要使用私有变量属性访问? [英] Why should I use a private variable in a property accessor?

查看:255
本文介绍了为什么要使用私有变量属性访问?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很抱歉,如果我是小白,我有这样的疑问,为什么我们使用私有变量和使用属性设置它们?

Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ?

为什么我们不能只使用性质在一个人吗?

Why can't we just use properites alone ?

我说的是这样的情况。

private string _testVariable;

public string MyProperty
{
    get { return _testVariable;}
    set {_testVariable = value;}
}

我想简单地使用

public string MyProperty { get; set; }

为什么多余的私有变量?在这两种策略有什么不同?任何人都可以请扔在这一些轻。

Why redundant private variable? are these two strategies different ? can anyone please throw some light on this.

感谢

推荐答案

您的例子是语义上是相同的。简洁的属性声明语法(只是有 {获取;设置;} )是在C#3.0中提供的快捷方式。编译器实际上是创建一个私有的后盾变量和一个简单的getter和setter作为你的第一个例子。

Your examples are semantically the same. The concise property declaration syntax (just having { get; set; }) is a shortcut available in C# 3.0. The compiler actually creates a private backing variable and a simple getter and setter as in your first example.

如果你正在做的是创造一个getter和setter(并没有什么要么发生在实际发生),那么简洁的语法是一个不错的选择。如果必须执行任何其他操作(重绘控件,例如)当你设置的值,则需要完整的语法。

If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required.

这篇关于为什么要使用私有变量属性访问?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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