2013-04-09 86 views
-1

我有以下類;c#List <Class> Additions

abstract class People 
    { 
    string name; 
    bool disabled; 
    string hometown; 

    Hometown referenceToHometown; 


    // default constructor 
    public People() 
    { 
     name = ""; 
     disabled = false; 
     hometown = ""; 
    } 

我想將數據添加到它,在對形式稍後的時間顯示 - 研究後,我有這個,但我得到了一些錯誤「無效令牌‘=’」

namespace peoplePlaces 
{ 
public partial class frm_people : Form 
{ 
     List<People> people = new List<People>(); 

     People data = new(); 
     data.name = "James"; 
     data.disabled = false; 
     data.hometown = "Cardiff" 

     people.Add(data); 
} 

}

這是否有一種更好的方法來將數據添加到類中?這樣做可以通過記錄循環表格嗎?

任何幫助將不勝感激!

+4

你的課是抽象的。你不能實例化它。此外,你錯過了一個分號。 – voithos 2013-04-09 15:18:08

+1

此外,您錯過了在'new'後面實例化的類型 – Rik 2013-04-09 15:18:56

+2

但是,錯誤消息指向的是您嘗試實例化對象並在類的主體中調用方法。你不可以做這個;類體是用於*定義*(例如字段,方法)。 – voithos 2013-04-09 15:19:38

回答

1

修訂代碼你正在試圖做的:

public class People 
{ 
    public string Name { get; set; } 
    public bool Disabled { get; set; } 
    public string Hometown { get; set; } 

    Hometown referenceToHometown; 


// default constructor 
public People() 
{ 
    name = ""; 
    disabled = false; 
    hometown = ""; 
} 

public People(string name, bool disabled, string hometown) 
{ 
    this.Name = name; 
    this.Disabled = disabled; 
    this.Hometown = hometown 
} 

和你的網頁代碼:

namespace peoplePlaces 
{ 
    public partial class frm_people : Form 
    { 
     // This has to happen in the load event of the form, sticking in constructor for now, but this is bad practice. 

     public frm_people() 
     { 
     List<People> people = new List<People>(); 

     People data = new Person("James", false, "Cardiff"); 

     // or 

     People data1 = new Person { 
      Name = "James", 
      Disabled = false, 
      Hometown = "Cardiff" 
     }; 

     people.Add(data); 
     } 
    } 
} 
1

您可以使用靜態方法來執行這種初始化:

public partial class frm_people : Form 
{ 
    List<People> people = CreatePeople(); 

    private static List<People> CreatePeople() 
    { 
     var list = new List<People>(); 

     People data = new People(); 
     data.name = "James"; 
     data.disabled = false; 
     data.hometown = "Cardiff"; 

     list.Add(data); 

     return list; 
    } 
} 

當然,你的People類型將不得不作出非抽象的,否則你就必須創建一個非實例抽象派生類型;現在您不能使用new People()創建People的實例,因爲該類標記爲抽象。

如果您使用的是現代的足夠C#中,你可以做到這一點只使用初始化構造:

public partial class frm_people : Form 
{ 
    List<People> people = new List<People>() { 
     new People() { 
      name = "James", 
      disabled = false, 
      hometown = "Cardiff" 
     } 
    }; 
} 
0

您的People類看起來像這可能是您在C#中的第一個類之一。你應該從小事做起,只有當你需要的時候添加功能:

class People 
{ 
    string Name { get; set; } 
    bool Disabled { get; set; } 
    string Hometown { get; set; } 
    Hometown ReferenceToHometown { get; set; } 
} 

然後你可以這樣調用它:

People data = new People() { Name = "James", Disabled = false, Hometown = "Cardiff" }; 

如果你需要抽象類和構造函數,那麼當你需要將它們添加他們。