c# - C#中的类可以指向它自己吗

标签 c#

我有一个 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/

相关文章:

c# - 东亚本地化软件中的访问/快捷键?

c# - C#计算两年间的闰年数

c# - 复杂服务层 IoC 的最佳实践

c# - 当使用自定义契约(Contract)解析器而不是 JsonConverter 属性时,自定义 JsonConverter 被忽略以进行反序列化

c# - 比较两个托管引用

c# - 隐式等待?

c# - 书籍索引的序列和 Rangify 列表

c# - ASP.NET MVC3 和 MongoDB

c# - 为什么我在定义自定义配置文件时收到 TypeLoadException?

c# - Mediatr 无法解析 ASP.Net Core 中的 UserManager