1. Access modifiers for members in class
The orientation modifier is to determine the area that the member can access (used). Commonly used in C# are the following modifiers: pubic (pubic), private (private), internal (inline), and protected (protected). Give examples of the restricted areas of each modifier.
Copy the codeThe code is as follows:
class TestClass
{
public int a = 0;
private int b = 0;
protected int c = 0;
pulic static int d=0;
}
In the TestClass class, the variable a is a public type, which can be used outside the class, that is, the class can be instantiated; the variable b can only be accessed within the class, that is, the functions inside the class can be used b; the variable c is the TestClass inherited class that can be used.
Copy the codeThe code is as follows:
class B
{
private void st()
{
TestClass tec = new TestClass();
int aa = ; //right
int bb = ; //wrong
int cc = //wrong
}
TestClass Instantiate the object tec, tec can access a but cannot access b and c. So under what circumstances can b and c be accessed?
Copy the codeThe code is as follows:
class C:TestClass
{
private void st()
{
TestClass tec = new TestClass();
C bo = new C();
int aa = ;
int bb = ;//wrong
int cc = ;//wrong
int tt = ;
}
}
Let’s talk about c first. c is a protected type whose inheritance class C is accessible. It is the instantiated object of class B. It is still inaccessible. But B can access c inside. As shown below, there is no limit on accessing within a class.
Copy the codeThe code is as follows:
class TestClass
{
public int a = 0;
private int b = 0;
protected int c = 0;
pulic static int d=0;
private void os()
{
int a1 = a;
int a2 = b;
int a3 = c;
}
}
After B inherits, c becomes private. In other words, the inheritance class of B cannot access c; as shown below, c cannot be accessed in D.
Copy the codeThe code is as follows:
class D : B
{
private void st()
{
B bo = new B();
int dd = ;//wrong access is restricted
}
}
The static modifier indicates that the field or method is owned by a class and is not a specific object. The values of a, b, and c are different when the TestClass class are instantiated, but d is the same. If a, b, and c are equivalent to the province each person is in, then d means that everyone is in China.
Copy the codeThe code is as follows:
class B:TestClass
{
TestClass tec = new TestClass();
int bb = ;//wrong The reason for the error is that the field's initial value refers to a non-static field
int cc = ;
private void st()
{
B bo = new B();
int aa = ;
int tt = ;
}
}
summary:
public modification: both inside and outside the class; private: inside; protect: inside the class is its derived class.