简体   繁体   中英

Property getter setter in C#

I have a class library project. I have a property there like below. It's not a read only property

 private   Int32 ABC  ;
public Int32   ABCD
        {
            set
            {
                this.ABC = value;
            }
            get
            {
                return this.ABC;
            }
        }

My question is, Is it necessary to declare the private variable for the same and the getter / setter ?

EDIT

I mean could it be like below ?

public Int32 ABCD {}

Automatic property declarations require the get; set; get; set; statements in the braces (which is what you had in your original question):

public Int32 ABCD { get; set; }

An empty property block isn't valid.

Use auto-implemented properties introduced in C# 3.0 (VS 2008) or later.
http://msdn.microsoft.com/en-us/library/bb384054.aspx

public Int32 Abcd {get;set;}

The compiler creates the backing field for you. However it is anonymous and cannot be accessed. If later on you find the need to access the backing field, you can explicitly declare it and reimplement the getter and setter using that field without breaking your interface.

Use auto implemented property, It interduced from 2008 :

    public Int   ABCD
    {
        set;
        get;
    }

But difference is default value, ie in property with backing field you can set a default value in variable but in this case default is .net defaults. (in fact you should initiate it in constructor for default value).

如果您选择第二个,C#将为您创建第一个。

Is it necessary to declare the private variable for the same and the getter / setter ?

If you mean is it necessary to use the private variable then yes, it is (unless you use the automatic method mentioned by BoltClock).You should keep in mind that it is a full code block, so you can do pretty much anything you like in there - although you should do it within reason, as you don't want anything that is going to slow down the access to the properties too much.

For example, there can be side effects to changing a property, ie another property may have to be updated, or you may have to notify that other properties have changed as well.

If you are not notifying or doing anything else, then the automatic getter/setter method is the quicker to develop (that is not claiming it is the fastest (or slowest) to execute though).

你可以这样

public string ABCD { get;set;}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM