简体   繁体   中英

Understanding Get and Set Accessors

I'm a newbie and I'm trying to learn the basics of C#. This might sound quite trivial and may be stupid but its a doubt. While going through one of the source codes of an application, I saw a piece of code inside a class

private string fname;
public string FirstName
{
    get
    {
       return fname
    }
    set
    {
       fname = value;
    }
}

Can anyone tell me what it means. I understand that when we declare a class we access fname using an alias FirstName . If it's for some security purpose then what?

This code is also equivalent to:

public string FirstName { get; set; }

What this do is define a property . In C# properties provide encapsulation for private fields .

You can write your custom logic on your property. Fe, some validation:

public string FirstName
{
    get
    {
       return fname;
    }
    set
    {
       if (value.Count(s => Char.IsDigit(s)) > 0)
       {
           throw new Exception("Only letters allowed");
       }
       fname = value;
    }
}

fname是一个字段,具有私有可见性,但FirstName是一个公共属性,因此它将在类外部可见,并且可以在get和set方法中包含逻辑

It's called Properties ( MSDN article ). The reason for using them is to encapsulate accessing some class field to be able to easily change class behavior in future if needed.

This is also equivalent to so called auto-property, since the property at this moment oftimedoes not add any logic:

public string FirstName { get; set; }

get and set methods are called accessors(getters) and mutators(setters) these methods are used to access and mutate the attributes of an object without allowing the access from outside the class. See that access modifier of the variable fname is private which means it can only be accessed by any method inside the class.

and note that the get and set methods should normally be given the public access modifier which enables the method to be accessed from any outside class.

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