簡體   English   中英

C#:自定義2維數組麻煩

[英]C#: Custom 2-dim arrays trouble

我正在嘗試使用以下代碼創建自定義類Cell的二維數組:

public class Cell
{
    int top;
    int bottom;
}

public Form1()
{
    Cell[,] elements;
    elements = new Cell[10,10];

    Random r = new Random();

    for (int i=0; i!=10; i++)
    {
        for (int j=0; j!=10; j++)
        {
            elements[i,j].top = r.Next();
        } 
    }
}

但是我總是收到以下錯誤:可訪問性不一致:...以及有關“單元不易訪問”的一些信息...

如何正確定義自定義類的二維數組?

我懷疑您實際上還沒有足夠的代碼。 我懷疑您在實際代碼中沒有在Cell聲明中留下“ public”,而您在簽名中的某處使用了public方法。 像這樣:

class Cell { ... }

public class Foo
{
    public Cell[,] DoStuff()
    {
    }
}

另外,也可以將Cell作為公共類,但嵌套在非嵌套類中。

我不認為它與數組有任何關系。

但是,如果您發布完整的錯誤消息而不是“與之相關的東西”,則將更加清晰。如果您發布簡短但完整的程序來演示問題,這也將有所幫助。

編輯:正如其他人指出的那樣,您發布的代碼無法編譯,但是出於不同的原因。 我懷疑您是否編寫了有關不一致的可訪問性的錯誤消息,所以我強烈懷疑您發布的代碼實際上根本不像您的真實代碼-至少在可訪問性方面。

同樣,在沒有看到真實代碼的情況下,很難給出准確的答案。

屬性的默認可訪問性是私有的。 嘗試這個:

public class Cell
{
    public int top;
    public int bottom;
}

更好的是,使它們具有自動屬性:

public class Cell
{
    public int top { get; set; }
    public int bottom { get; set; }
}

可訪問性錯誤與數組創建無關。 該錯誤最常見的場景是帶有私有或內部類型參數的公共方法。

我建議您使屬性超出topbottom字段。 它們具有private訪問權限,因此會出現錯誤:

public class Cell
{
    public int top { get; set; };
    public int bottom { get; set; };
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM