-1

我有以下课程;

    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

3 回答 3

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类型必须是非抽象的,或者你必须创建一个非抽象派生类型的实例;现在您不能创建Peopleusing的实例new People(),因为该类被标记为抽象。

如果您使用的是足够现代的 C#,则可以仅使用初始化构造来执行此操作:

public partial class frm_people : Form
{
    List<People> people = new List<People>() {
        new People() {
            name = "James",
            disabled = false,
            hometown = "Cardiff"
        }
    };
}
于 2013-04-09T15:18:34.157 回答
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);
        }
   }
}
于 2013-04-09T15:23:06.253 回答
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" };

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

于 2013-04-09T15:24:02.613 回答