我有一個 C# 類,比方說:
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"}
}
該結構定義了一個國家及其鄰國。
聯合國是許多國家的集合。
為了簡化問題,我們假設一個國家只能有 1 個或沒有鄰居。COUNTRY 型別的變數可以通過宣告輕松地在 C 中啟動。
C#有類似的能力嗎?
uj5u.com熱心網友回復:
類(通常)是參考型別。因此,您使用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;
}
}
}
}
uj5u.com熱心網友回復:
首先,定義你的類:
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(法國)。
IC#,當你使用一個類(而不是結構)時,你的變數就像一個 C 指標,它是一個參考。在c1.neightbor = c1您將變數 neightbor 設定為c1. 如果你改變了c1.neightbor,你真的在??改變c1。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467137.html
標籤:C#
下一篇:Linq按狀態分割資料
