我有一个 C# 类(class),假设:
public class COUNTRY
{
COUNTRY * neighbor;
string countryName;
}
C# 提示它无法指向自身(错误代码:CS0208)
这在 C 中是允许的。例如:
typedef struct country
{
struct country *neighbor;
char[50] countryName;
} COUNTRY;
COUNTRY unitedNation[]
{
{COUNTRY a, "US"},
{COUNTRY b, "ABC"},
{COUNTRY c, "XYZ"},
{0,""}
}
COUNTRY a
{
{0, "Mexico"},
}
COUNTRY b
{
{0,"Findland"}
}
COUNTRY c
{
{0, "Australia"}
}
该结构定义了一个国家及其邻国。
unitedNation 是许多国家的集合。
为了简化问题,我们假设一个国家只能有 1 个邻居或没有邻居。 COUNTRY 类型的变量可以通过声明在 C 中轻松初始化。
C#有类似的能力吗?
最佳答案
类(通常)是引用类型。因此,您可以使用 new 创建实例,并且在函数调用中传递时,它们是通过“引用”(指针的一个奇特词)传递的。与引用类型相反,还有值类型,它们分别按值传递。
因此,您尝试执行的操作不需要特殊语法。
using System;
namespace slist
{
class SList {
internal SList Next {get; set;}
internal SList() {
Next = null;
}
internal SList(SList head) {
this.Next = head;
}
internal int V {get; set;}
}
class Program
{
static void Main(string[] args)
{
//Console.WriteLine("Hello World!");
SList head = new SList();
head.V = 1;
head = new SList(head);
head.V = 2;
head = new SList(head);
head.V = 3;
IterateSList(head);
}
static void IterateSList(SList head) {
SList current = head;
while (current != null) {
Console.WriteLine("{0:D}", current.V);
current = current.Next;
}
}
}
}
关于c# - C#中的类可以指向它自己吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72050623/