Set interface data set. Creating get and set methods Get and set methods

To control how fields are used, you can create get and set methods and make them public. They provide the ability to control access to a field. At the same time, it is better to make the Age field private so that it cannot be directly accessed outside the class.

public class Account

private int age;

public int GetAge()

return this.age;

public void SetAge(int inAge)

if ((inAge > 0) && (inAge< 120))

this.age = inAge;

Now we can control access to our field, but this requires writing a lot of additional code. In order to access the age value, you need to call the created methods:

Account s = new Account();

Console.WriteLine("Age: " + s.GetAge());

    1. Using Properties

Properties make data management easier. The Age property can be declared as follows:

public class Account

private int ageValue;

if ((value > 0) && (value< 120))

ageValue = value;

return ageValue;

Here the age value is a property. The property declares sections for writing and reading its value. The actions described in these sections are equivalent to the methods described previously. In this case, properties are used in the same way as regular fields:

Account s = new Account();

Console.WriteLine("Age: " + s.Age);

When the Age property is set to a value, the set section code is called. The value keyword denotes the value that is assigned to the property. When reading the value of the Age property, the get section code is called. This approach combines the advantages of using methods and allows you to work with properties as easily as with class fields.

Checking the correctness of data in properties . If you try to set an invalid age value (for example, 150), the above code will perform a validity check and reject the value (no one over 120 years old can have an account with our bank), leaving the old age value. The only way to know if a property has been assigned a value is to check the property's value after this operation:

Account s = new Account();

int newAge = 150;

if (s.Age != newAge)

Console.WriteLine("The age value was not set");

The following code attempts to set age to an invalid value of 150 and then checks to see if that value was set. If the Set method were used to assign the value, it could return the value false If this fails, then using the property requires the user to do a little more extra work.

Different ways to read a property value. Properties allow you to perform other useful actions.

public int AgeInMonths

return this.ageValue * 12;

The new AgeInMonths property is described here. It is read-only because it does not contain a set section. It returns the age value in months, using the same value as the Age property. This means that you can use several in various ways to get the same value. It is possible to create read-only properties without being able to change them directly, as well as write-only properties, although the latter are rarely used.

Properties of visual elements . It makes sense to use properties in the description of a bank account, where you need to protect data in objects. But in Silverlight, you can enter any text into a TextBlock element, and there seems to be no need to check the validity of the entered value. Running this code will slow down the value entry process. So, by making the Text value a public string, the program would contain less code and run faster.

But when we change the text in the TextBlock element, we want the text on the Silverlight page to also change, for example when the Adder program displays the result. If the program simply changed the value of the field, Silverlight would have no way of knowing that the message on the screen needed to be updated.

However, if Text is made a property, when the value of the TextBlock element is updated, the corresponding method will run, which can update the stored value of the text box and call a method to update the screen to display the new value. Properties provide the ability to manipulate an object when its value changes. Simple operation:

resultTextBlock.Text = "0";

can result in several hundred C# operations because storing the new value in the TextBlock element triggers operations to update the screen image.

Joseph Crawford, one of my readers, read an article about how I don't like writing getters and setters and suggested that I could use the magic __get and __set methods.
I'll tell you why it's not a good idea to use them in the normal way. I'm also going to tell you a story where they really came in handy - creating static types in PHP (a dynamic language).
For those unfamiliar with the __get and __set methods, they are two "magic" methods that work like this:
class Animal ( function __get($property) ( //... ) function __set($property, $value) ( ​​//... ) ) $cow = new Animal; $cow->weight = "1 ton"; // same as $cow->__set("weight", "1 ton") print $cow->weight; // same as print $cow->__get("weight");

Typically, the above methods are used to create dynamic properties. What conclusion can be drawn from this? If you want to create any random properties, just use a hash (aka an array with keys).
What's good about getters and setters?
Let's get a look:
class Animal ( public $weightInKgs; ) $cow = new Animal; $cow->weightInKgs = -100;

What? Negative weight? This is from most points of view incorrect.
A cow should not weigh less than 100 kg (I think so:). Within 1000 is acceptable.
How can we ensure such a limitation?
Using __get and __set is quite quick way.
class Animal ( private $properties = array(); public function __get($name) ( if(!empty($this->properties[$name])) ( return $this->properties[$name]; ) else ( throw new Exception("Undefined property ".$name." referenced." ) ) public function __set($name, $value) ( ​​if($name == "weight") ( if($value< 100) { throw new Exception("The weight is too small!") } } $this->properties[$name] = $value;

) ) $cow = new Animal; $cow->weightInKgs = -100; // throws an Exception
What if you have a class with 10-20 properties and checks for them? In this case, troubles are inevitable.< 100) { throw new Exception("The weight is too small!") } if($this->public function __set($name, $value) ( ​​if($name == "weight") ( if($value

weight != $weight) ( Shepherd::notifyOfWeightChange($cow, $weight); ) ) if($name == "legs") ( if($value != 4) ( throw new Exception("The number of legs is too little or too big") ) $this->numberOfLegs = $numberOfLegs; $this->numberOfHooves = $numberOfLegs; ) if($name == "milkType") ( .... you get the idea ... . ) $this->properties[$name] = $value; ) Conversely, getters and setters manifest themselves with
the best side< 100) { throw new Exception("The weight is too small!"); } if($this->weight != $weight) ( Shepherd::notifyOfWeightChange($cow, $weight); ) $this->weight = $weight;

) public function getWeight() ( return $this->weight; ) )
Nothing compares to the shortcut functions (get, set;) from C#. It’s likely that such support will appear in PHP soon, but for now let’s not relax...
Each method is responsible only for its own area, making the code easier to navigate. It's still a lot of code, but it's cleaner than the __set version. There is a good heuristic approach, which is as follows: if your method (function) takes up more than 1 screen, you need to shorten it. This will make the code easier to read.
We also store some business logic. There will always be exactly as many hooves as there are legs, and if we notice a change in the weight of the cattle, we will immediately notify the shepherd.
Since we don't care about cow nicknames or check them, let the data be public without getters and setters.
Again, I didn't really write all these getters and setters - PHP Storm did it for me. I simply wrote the following:

class Animal ( private $weight; private $numberOfLegs; )
And pressed Alt+Insert -> Getters and setters. PHPStorm generated everything automatically.

Now, as an added benefit of PHP Storm, when working with getters and setters, I have the ability to use the autocomplete function:
In the case of __get I don't have this option, I can only write this:

$cow->wieght = -100
Now the cow “weighs” (wIEghts) minus 100 kg.
I can forget that this is weight in kg, just write weight and everything will work.
So, getters and setters can be very useful (but still don’t worship them, you’re not a Java programmer). If you just want free properties, use an array:

$cow = array("weight" => 100, "legs" => 4);
This trick is much easier to pull off than __get and __set.
The __set method has another drawback. It only accepts 1 parameter. What if you need 2? For example, like here: $store1->setPrice("item-1", 100). You need to set the price of the product in the store. The __set method won't allow you to do this, but the setter will.

Last update: 07/29/2018

In addition to regular methods, the C# language provides special access methods called properties. They provide easy access to class fields, find out their value, or set them.

The standard property description has the following syntax:

[access_modifier] return_type custom_name ( // property code )

For example:

Class Person ( private string name; public string Name ( get ( return name; ) set ( name = value; ) ) )

Here we have a private name field and a public Name property. Although they have almost the same name except for the register, this is nothing more than a style; their names can be arbitrary and do not necessarily have to match.

Through this property we can control access to the name variable. The standard property definition contains get and set blocks. In the get block we return the value of the field, and in the set block we set it. The value parameter represents the value to be passed.

We can use this property like this:

Person p = new Person(); // Set the property - the Set block is triggered // the value "Tom" is the value passed to the property p.Name = "Tom"; // Get the value of the property and assign it to a variable - the Get string personName = p.Name block is triggered;

Perhaps the question may arise, why do we need properties if we can get by with ordinary class fields in this situation? But the properties allow you to invest additional logic, which may be necessary, for example, when assigning a value to a class variable. For example, we need to set up an age check:

Class Person ( private int age; public int Age ( set ( if (value< 18) { Console.WriteLine("Возраст должен быть больше 17"); } else { age = value; } } get { return age; } } }

The set and get blocks do not have to be present in a property at the same time. If a property is defined only by a get block, then the property is read-only - we can get its value, but not set it. Conversely, if a property only has a set block, then that property is writable only - you can only set the value, but you cannot get it:

Class Person ( private string name; // read-only property public string Name ( get ( return name; ) ) private int age; // write-only property public int Age ( set ( age = value; ) ) )

Access modifiers

We can apply access modifiers not only to the entire property, but also to individual blocks - either get or set:

Class Person ( private string name; public string Name ( get ( return name; ) private set ( name = value; ) ) public Person(string name, int age) ( Name = name; Age = age; ) )

Now we can use the closed set block only in this class - in its methods, properties, constructor, but not in another class:

Person p = new Person("Tom", 24); // Error - set is declared with the private modifier //p.Name = "John"; Console.WriteLine(p.Name);

When using modifiers in properties, there are a number of restrictions to consider:

    A modifier for a set or get block can be set if the property has both set and get blocks.

    Only one set or get block can have an access modifier, but not both

    The access modifier of a set or get block must be more restrictive than the access modifier of a property. For example, if a property has the modifier public, then the set/get block can only have the modifiers protected internal, internal, protected, private

Encapsulation

We saw above that access to private class variables is established through properties. Hiding the state of a class from outside interference in this way represents the mechanism of encapsulation, which represents one of the key concepts of object-oriented programming. (It is worth noting that the very concept of encapsulation has quite a few different interpretations, which do not always overlap with each other) The use of private access modifiers protects a variable from external access. To control access, many programming languages ​​use special methods, getters and setters. In C#, their role is usually played by properties.

For example, there is some Account class that defines a sum field representing a sum:

Class Account ( public int sum; )

Since the sum variable is public, we can access it anywhere in the program and change it, including setting any invalid value, for example, negative. It is unlikely that such behavior is desirable. Therefore, encapsulation is used to restrict access to the sum variable and hide it inside the class:

Class Account ( private int sum; public int Sum ( get (return sum;) set ( if (value > 0) ( sum=value; ) ) ) )

Automatic properties

Properties control access to the fields of a class. However, what if we have a dozen or more fields, then defining each field and writing a property of the same type for it would be tedious. Therefore, automatic properties were added to the .NET framework. They have a shortened declaration:

Class Person ( public string Name ( get; set; ) public int Age ( get; set; ) public Person(string name, int age) ( Name = name; Age = age; ) )

In fact, fields for properties are also created here, only they are not created by the programmer in the code, but the compiler automatically generates them during compilation.

What is the advantage of auto-properties, if in essence they just access an automatically created variable, why not directly access a variable without auto-properties? The fact is that at any time, if necessary, we can expand the auto-property into a regular property and add some specific logic to it.

It is worth considering that you cannot create an automatic write-only property, as is the case with standard properties.

Auto-properties can be assigned default values ​​(initializing auto-properties):

Class Person ( public string Name ( get; set; ) = "Tom"; public int Age ( get; set; ) = 23; ) class Program ( static void Main(string args) ( Person person = new Person(); Console .WriteLine(person.Name); // Tom Console.WriteLine(person.Age); // 23 Console.Read();

And if we do not specify the values ​​of the Name and Age properties for the Person object, then the default values ​​will apply.

Auto properties can also have access modifiers:

Class Person ( public string Name ( private set; get;) public Person(string n) ( Name = n; ) )

We can remove the set block and make the auto property read-only. In this case, to store the value of this property, a field with the readonly modifier will be implicitly created for it, so it should be taken into account that such get-properties can be set either from the class constructor, as in the example above, or when initializing the property:

Class Person ( public string Name ( get;) = "Tom" )

Shorthand notation for properties

Just like methods, we can shorten properties. For example:

Class Person ( private string name; // equivalent to public string Name ( get ( return name; ) ) public string Name => name; )



2024 wisemotors.ru. How it works. Iron. Mining. Cryptocurrency.