簡體   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