为什么我们需要创建一个类变量来获取和设置的属性? [英] Why do we need to create class variables to get and set a property?

查看:163
本文介绍了为什么我们需要创建一个类变量来获取和设置的属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

很简单的问题,但我觉得很重要的是要明白我们为什么这么做

Very simple question but I find it very important to understand why we do it.

我可以按如下方式在类中创建一个属性:

I can create a property in the class as follows:

1的方法:

public class MyClass
{
   public string MyProperty {get;set;}
}

第二做法:

public class MyClass
{
private string _myProperty;

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



几乎所有的文章使用后一种方法。为什么我们需要在类中创建一个临时变量来保存字符串值。为什么我们不能只使用第一种方法?请问第二种方法提供任何好处?是不是坏的内存和性能明智的创造额外的变量来存储值

Almost all of the articles use the later approach. Why do we need to create a temporary variable in the class to hold the string value. Why can't we just use the first approach? Does the second approach provide any benefits? Isn't it bad memory and performance wise to create extra variable to store a value?

推荐答案

Automatic性能未添加到C#,直到C#3.0中,这样的例子很多或物品使用后的形式被写入之前,C#3.0来了出。除非你需要做额外的工作在你的财产的getter和setter,没有理由去选择一个比其他。

Automatic properties were not added to C# until C# 3.0, so many examples or articles which use the later form were written before C# 3.0 came out. Unless you need to do extra work in your property setters and getters, there is no reason to choose one over the other.

这篇关于为什么我们需要创建一个类变量来获取和设置的属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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