Encapsulation refers to hiding the internal data of a class from being manipulated directly by an object instance, and in C # provides a property mechanism to manipulate the state inside the class.
Encapsulation in C # can be represented by keywords such as public, private, protected, and internal.
Why encapsulate the inside of a class?
Cases:
public class Person
{
public string name;
public int age;
}
If I instantiate this class above
Person P=new person ()
So I assign a negative to age, which is clearly not in line with the business logic, is the person's age likely to be negative?
P.age= "-1"
After using encapsulation
public class Person
{
private string name;
public string Name
{
Get{return name;}
Set{name=value;}
}
private int age;
public string Age
{
Get{return age;}
set{
if (value>0)
{
Age=value; The age is controlled, and the age must be greater than 0 to assign a value. Then the age of 1 is not assignable.
}
Else
{
Throw (New ArgumentException ("Error", Value, "Age cannot be negative"));//Throws an exception here
}
}
}
}
Once encapsulated, the object instance can only manipulate properties, and the properties may be controlled by writing down their own logic.
C # Object-oriented encapsulation