C writes read only attribute instance analysis on classes

  • 2020-06-23 01:49:55
  • OfStack

Attributes in C# are intended to encapsulate fields for the security of program data. This article examines the write-only property in C# as an example.

For read-only or write-only property definitions:

1. Read only or write only without writing one of the get\set methods

Such as:


private int a;
public int A{
get
{
  return a;
  }
}

2, private for protection, outside the class also means read-only or write-only

Such as:


private int a;
public int A{
private get
{
  return a;
}
set
{
  a = value;
}
}

It is important to note here that the properties defined in this way are in C# 3.0 and later, and are automatically implemented to make property declarations more concise when no additional logic is required in the property's accessors.

The compiler creates a private anonymous support field that can only be accessed through the get and set accessors of the property,


public int A{get;set;}

Remember that! In this way, one of the items (get/set) cannot be omitted for read-only or write-only.

But with private protection:


public int A{get;private set;}

Related articles: