我有以下课程;
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);
}
}
这是否有一种更简洁的方法来向类中添加数据?这样做可以形成一个循环记录吗?
任何帮助都会非常感谢!
答案 0 :(得分: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
类型必须是非抽象的,否则您将不得不创建非抽象派生类型的实例;现在你无法使用People
创建new People()
的实例,因为该类被标记为抽象。
如果您使用的是足够现代的C#,则只能使用初始化结构:
public partial class frm_people : Form
{
List<People> people = new List<People>() {
new People() {
name = "James",
disabled = false,
hometown = "Cardiff"
}
};
}
答案 1 :(得分: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);
}
}
}
答案 2 :(得分: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" };
如果需要抽象类和构造函数,则应在需要时添加它们。