c#列表<;类别>;添加物

c#列表<;类别>;添加物,c#,list,class,C#,List,Class,我有以下课程 abstract class People { string name; bool disabled; string hometown; Hometown referenceToHometown; // default constructor public People() { name = ""; disabled = false; hometown =

我有以下课程

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

    Hometown referenceToHometown;


    // default constructor
    public People()
    {
        name = "";
        disabled = false;
        hometown = "";
    }
我想向它添加数据,以便稍后在表单上显示-经过研究,我有了这个,但得到了一些错误“无效令牌”=”

命名空间peoplePlaces
{
公共部分类frm_人员:表格
{
列表人员=新列表();
人员数据=新的();
data.name=“James”;
data.disabled=false;
data.homely=“加的夫”
添加(数据);
}
}

这是向类添加数据的更简洁的方法吗?在这样做的过程中,是否可以制作一个表格来循环记录


任何帮助都将不胜感激

您可以使用静态方法执行此类初始化:

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;
    }
}

修改了您尝试执行的操作的代码:

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);
        }
   }
}
命名空间peoplePlaces
{
公共部分类frm_人员:表格
{
//这必须发生在表单的加载事件中,目前仍停留在构造函数中,但这是一种糟糕的做法。
公共财政部人员()
{
列表人员=新列表();
人员数据=新人(“詹姆斯”,假,“加的夫”);
//或
人员数据1=新人员{
Name=“詹姆斯”,
禁用=错误,
家乡=“加的夫”
};
添加(数据);
}
}
}

您的人物类看起来可能是您在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" };

如果您需要抽象类和构造函数,则应在需要时添加它们。

您的类是抽象的。你不能实例化它。此外,您还缺少分号。此外,您还缺少在
new
之后要实例化的类型,但错误消息所指的是您正在尝试实例化对象并调用类体中的方法。你不能这样做;类主体用于定义(例如字段、方法)。
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" };