Explain the attributes and the use of attributes in C in detail

  • 2021-09-05 00:40:47
  • OfStack

Attribute
Property is a member that provides a flexible mechanism to read, write, or evaluate the value of a private field. Attributes can be used as public data members, but they are actually special methods called "accessors." This makes it easy to access data, and it also helps to improve the security and flexibility of methods.
In this example, the TimePeriod class stores time periods. This class internally stores time in seconds, but an attribute named Hours allows clients to specify time in hours. The accessor of the Hours property performs the conversion between hours and seconds.


class TimePeriod
{
  private double seconds;

  public double Hours
  {
    get { return seconds / 3600; }
    set { seconds = value * 3600; }
  }
}


class Program
{
  static void Main()
  {
    TimePeriod t = new TimePeriod();

    // Assigning the Hours property causes the 'set' accessor to be called.
    t.Hours = 24;

    // Evaluating the Hours property causes the 'get' accessor to be called.
    System.Console.WriteLine("Time in hours: " + t.Hours);
  }
}

Output:


Time in hours: 24

Expression body definition
Attributes that directly return only the results of expressions are common. The following syntax shortcut uses = > To define these attributes:


public string Name => First + " " + Last; 

Attribute must be read-only, and you cannot use the get accessor keyword.

Using attributes
Properties combine many aspects of fields and methods. For users of objects, properties are displayed as fields, and the same syntax is required to access them. For the implementer of the class, the attribute is one or two code blocks representing one get accessor and/or one set accessor. Execute the code block of get accessor when reading attributes; Executes the code block of the set accessor when 1 new value is assigned to the property. Attributes that do not have an set accessor are considered read-only. Attributes that do not have an get accessor are treated as write-only attributes. Attributes with both accessors are read-write attributes.

Attributes have many uses: they can validate data before allowing changes; They can transparently expose data on a class that is actually retrieved from another source, such as a database; When data is changed, they can take action, such as raising an event or changing the value of another field.
Attributes are declared in a class block by specifying the access level of the field, then specifying the type and name of the attribute, followed by the code block declaring an get accessor and/or an set accessor. For example:


public class Date
{
  private int month = 7; // Backing store

  public int Month
  {
    get
    {
      return month;
    }
    set
    {
      if ((value > 0) && (value < 13))
      {
        month = value;
      }
    }
  }
}

In this example, Month is declared as a property, so that the set accessor can ensure that the Month value is set between 1 and 12. The Month property uses a private field to track the actual value. The real location of the data of an attribute is often called the "backing store" of the attribute. It is common for properties to use private fields as backing stores. Marking a field as private ensures that it can only be changed by calling properties.

.
get accessor
The get accessor body is similar to the method body. It must return a value of the attribute type. Executing the get accessor is equivalent to reading the value of the field. For example, when a private variable is being returned from an get accessor and optimization is enabled, the call to an get accessor method is inlined by the compiler, so there is no overhead for method invocation. However, the virtual get accessor cannot be inline because the compiler does not know at compile time which method is actually called at run time. The following is an get accessor that returns the value of the private field name:


class Person
{
  private string name; // the name field
  public string Name  // the Name property
  {
    get
    {
      return name;
    }
  }
}

When a property is referenced, the get accessor is called to read the value of the property unless the property is the target of the assignment. For example:


Person person = new Person();
//...

System.Console.Write(person.Name); // the get accessor is invoked here

An get accessor must terminate with an return or throw statement, and control cannot leave the accessor body.
Changing the state of an object by using an get accessor is not a good programming style. For example, the following accessor has the side effect of changing the state of the object every time it accesses the number field.


private int number;
public int Number
{
  get
  {
    return number++;  // Don't do this
  }
}

The get accessor can be used to return field values, or to calculate and return field values. For example:


class Employee
{
  private string name;
  public string Name
  {
    get
    {
      return name != null ? name : "NA";
    }
  }
}

In the last 1 code snippet, if you did not assign a value to the Name property, it returned the value NA.
set accessor
The set accessor is similar to a method with a return type of void. It uses an implicit parameter called value, whose type is the type of the attribute. In the following example, the set accessor is added to the Name property:


class Person
{
  private string name; // the name field
  public string Name  // the Name property
  {
    get
    {
      return name;
    }
    set
    {
      name = value;
    }
  }
}

When assigning a value to a property, the set accessor is called with parameters that provide the new value. For example:


Person person = new Person();
person.Name = "Joe"; // the set accessor is invoked here        

System.Console.Write(person.Name); // the get accessor is invoked here

In the set accessor, it is wrong to use the implicit parameter name value for local variable declarations.

This example illustrates instance, static, and read-only properties. It accepts the employee's name from the keyboard, increments NumberOfEmployees by 1, and displays the employee's name and number.


Time in hours: 24
0

Output:


Time in hours: 24
1

This example shows how to access a property in a base class that is hidden by another property in a derived class that has the same name as 1.


Time in hours: 24
2

Output:


  Name in the derived class is: John, Manager
  Name in the base class is: Mary

Here are the main points from the previous example:
The property Name in the derived class hides the property Name in the base class. In this case, the new modifier is used in the property declaration of the derived class:


Time in hours: 24
4

The transformation (Employee) is used to access hidden properties in the base class:


Time in hours: 24
5

In this example, the Cube and Square classes implement the abstract class Shape and override its abstract Area property. Note the use of override modifiers on attributes. The program accepts the input side length and calculates the area of square and cube. It also accepts the input area and calculates the corresponding side lengths of squares and cubes.


Time in hours: 24
6

Output:


Time in hours: 24
7


Related articles: