Summary of the use of attributes and member variables in the C class

  • 2020-06-03 08:11:10
  • OfStack

Attributes are really no different from member variables; they represent a certain property of the class, which makes them easier to understand.

Problems to be noted in use:
1. The property name and variable name cannot be the same.

2, 1 general variables are private, attributes are public, attributes for the class to call, variables are limited to use within the class, feel encapsulation reflected better

A property must be associated with a variable that must be defined in the class.


 public int b // define 1 A property b
  {   
   get
   {
    return b;
   }
   set
   {
    b = value;// right b The assignment 
   }

The result is an endless loop and stack overflow error.C++ aspects turn to C# when confused for a long time, normal use

Define the class A


public class A
 {
  private int b1 = 1;// Defined here 1 A variable 
  public int b           // Defined here 1 A property 
  {   
   get
   {
    return b1;// Attributes are associated with variables 
   }
   set
   {
    b1 = value;
   }
  }

  public A(int n)
  {
   b1 = n;
  }  
 }

In fact, you can program it exactly the way C++ does, and you can do it without any attributes at all.


Related articles: