对于第二个问题,在 C# 中,类的实例始终是 reference variable。 (我建议您在互联网上阅读更多相关信息)。因此,在示例中:
class Student
{
Student st1;
}
str1 可以引用 RAM 中的一个区域。你可以把它想象成一个指向矩形的箭头。箭头是引用矩形的变量,矩形是 RAM 上的位置。通过在类本身内部创建一个类的实例,我们实际上创建了一个指向新矩形的箭头,该矩形也有一个可以引用矩形的箭头,依此类推。
例如,创建节点列表很有用。每个节点引用另一个节点,如下所示:
class Node
{
public int number;
public Node next; // Here we create a new arrow to a new rectangle, which has an arrow too
}
在Main 方法中:
Node first = new Node();
first.number = 1;
Node second = new Node();
second.number = 2;
first.next = second; // Here we "match" the arrow to a rectangle. The arrow is "first.next", and the rectangle is "second".
Node third = new Node();
third.number = 3;
second.next = third;
// We have a list: 1 -> 2 -> 3 -> null
// The end of the list is null, becuase third.next references to null (it references to no "rectangle")
我们可以用不同的方式来做:
Node first = new Node();
first.number = 1;
first.next = new Node();
first.next.number = 2;
first.next.next = new Node();
first.next.next.number = 3;
// In this way, we have only the "head" of the list ("first"), but we can get any node that in the list by typing "first.next. ....... .next"
// We can also iterate over the list:
Node p = first;
while (p != null) // while we are not in the end of the list
{
// Do something, like "Console.WriteLine(p.number);" or "p.number++;"
p = p.next; // We go to the next node
}
这很有用,因为这个列表没有长度限制,我们可以轻松添加节点和删除节点。
例如:
public class Program
{
public static void Main(string[] args)
{
Node first = new Node();
int counter = 0;
first.number = counter;
counter++;
// Inialize a list of 10 nodes:
Node p = first; // We don't want to lost the "head" of our list, "first"
while (counter < 10)
{
p.next = new Node(); // We create a new node
p.next.number = counter; // And we initialize it
counter++;
p = p.next; // We go to the next node
}
// Now we print all the number in our list:
p = first; // We don't want to lost the "head" of our list, "first"
while (p != null)
{
Console.WriteLine(p.number);
p = p.next; // We go to the next node
}
}
}
输出:
0
1
2
3
4
5
6
7
8
9
希望对您有所帮助!