繁体   English   中英

class能否指向C#中的自身

[英]Can a class point to itself in 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 个邻国或没有邻国。 C可以很容易的通过声明来初始化COUNTRY类型的变量。

C#有没有类似的能力?

类(通常)是引用类型。 因此,您使用new创建实例,当在 function 调用中传递时,它们通过“引用”(指针的一个奇特词)传递。 相对于引用类型,还有值类型,分别是按值传递。

因此,您尝试执行的操作不需要特殊语法。

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;
            }
        }
    }
}

首先,定义您的 class:

public class COUNTRY
{
    public COUNTRY neighbor;
    public string countryName;
}

现在,试试这个示例:

COUNTRY c1 = new COUNTRY();
c1.neighbor = c1;
c1.countryName = "Spain";

COUNTRY c2 = new COUNTRY();
c2.neighbor = c1;
c2.countryName = "France";

c1.neighbor = c2;

您可以创建c1并将邻居引用设置为c1本身。 这是没有意义的,因为西班牙不是西班牙的邻居,但它是你的“指针”,你可以自动引用它。

我在c2之后为法国国家创建,并将西班牙设置为邻居。

最后,我修复了西班牙邻居,设置为c2 (法国)。

我 C#,当你使用 class(不是结构)时,你的变量就像一个 C++ 指针,它是一个引用。 c1.neightbor = c1中,您将变量 neightbor 设置为c1的地址。 如果你改变c1.neightbor ,你真的在改变c1

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM