2015-03-19 39 views
0

我正試圖在struct書中實現char數組。我已經在struct中聲明瞭char數組public char [] b_id = new char [3]。現在我想訪問b_id並初始化一些值。如何做呢。有什麼建議麼? 這是我現在的代碼。如何在C#中的Struct內使用char數組?

namespace @struct 
{ 
    struct Books 
    { 
     public string title; 
     public char[] b_id = new char[3]; 
    }; 
class Program 
{ 

    static void Main(string[] args) 
    { 

     Books Book1;  /* Declare Book1 of type Book */ 

     /* book 1 specification */ 
     Book1.title = "C Programming"; 


     /* print Book1 info */ 
     Console.WriteLine("Book 1 title : {0}", Book1.title); 

     Console.ReadKey(); 

    } 
} 
} 
+2

什麼地方在明顯的方式訪問它,你的問題?你得到了什麼錯誤? (暫時擱置,你有一個可變結構:http://stackoverflow.com/questions/441309/why-are-mutable-structs-vil) – HugoRune 2015-03-19 07:33:50

+1

爲什麼你使用可變結構和公共領域呢?如果可能,我會避免這樣做。不清楚你應該首先使用一個結構體......請提供更多關於*你爲什麼這麼做的信息......(我強烈建議不要使用一個關鍵字的命名空間...) – 2015-03-19 07:35:59

+0

潛在的重複:http://stackoverflow.com/questions/8158038/is-there-a-way-to-initialize-members-of-a-struct-without-using-a-constructor – HugoRune 2015-03-19 08:01:17

回答

0

您不能在結構中包含實例字段初始值設定項(即編譯器不允許您在Books結構中直接初始化您的b_id char數組)。 如果你這樣做,你的程序應該工作:

struct Books 
{ 
    public string title; 
    public char[] b_id; 
}; 

void Main() 
{ 

    Books book1;  /* Declare Book1 of type Book */ 
    book1.b_id = new char[3] {'a', 'b', 'c'}; 

    /* book 1 specification */ 
    book1.title = "C Programming"; 

    /* print Book1 info */ 
    Console.WriteLine("Book 1 title : {0}", book1.title); 
    Console.WriteLine("Book att : {0}", book1.b_id[0]); 

} 
+1

一個正確的回答一個負分數?我想downvoters往往懶得解釋他們的downvotes ... – 2015-03-19 09:01:41

+0

是的,我也很驚訝。即使這些問題並不總是最好的,我認爲SO用戶可能會更傾向於試圖學習如何編程的人 – 2015-03-19 09:23:42