我的代码段如下:
public class Database {
// fake class
public class databaseEntry
{
public Notification myNotification { get; set; }
private string myStatus { get; private set; }
}
// fake notifications
Notification notification1 = new Notification();
Notification notification2 = new Notification();
// fake database of type databaseEntry in List data structure
List<databaseEntry> myDatabase = new List<databaseEntry>();
// add fake data to fake database
myDatabase.Add( new databaseEntry() { myNotification = notification1, myStatus = "approved"});
myDatabase.Add( new databaseEntry() { myNotification = notification2, myStatus = "pending"});
}
目前的问题是CS0103:名称&#34; myDatabase&#34;在最后两行代码的当前上下文中不存在。
显然我已经实现了#d; myDatabase&#34;,所以我不明白为什么Visual Studio会这样说&#34; myDatabase&#34;不存在。
我粗鲁地跟着示例提供了 https://msdn.microsoft.com/en-us/library/3wcytfd1(v=vs.110).aspx
答案 0 :(得分:0)
使用ctor
每个都需要两个到现在的弹出列表
你没有myStaus,通知有问题
一个有自己列表的类是奇数
public class Database {
// fake class
public class databaseEntry
{
public Notification myNotification { get; set; }
private string myStatus { get; private set; }
}
// fake notifications
Notification notification1 = new Notification();
Notification notification2 = new Notification();
// fake database of type databaseEntry in List data structure
List<databaseEntry> myDatabase = new List<databaseEntry>();
public DataBase()
{
// need to do it in the ctor
// add fake data to fake database
myDatabase.Add( new databaseEntry(true) { myNotification = notification1, myStatus = "approved"});
myDatabase.Add( new databaseEntry(false) { myNotification = notification2, myStatus = "pending"});
}
public DataBase(bool skip)
{
}
}
答案 1 :(得分:0)
您必须将构造函数中的这些databaseEntry
项添加到List<T>
。在C#中无法以这种方式在类中添加它们。您可以创建一个类型的实例,但不能在其上调用方法。
public class Database {
//fake class
public class databaseEntry
{
public Notification myNotification { get; set; }
private string myStatus { get; private set; }
}
//constructor of your DataBase class
public DataBase(){
// add fake data to fake database
myDatabase.Add( new databaseEntry() { myNotification = notification1, myStatus = "approved"});
myDatabase.Add( new databaseEntry() { myNotification = notification2, myStatus = "pending"});
}
// fake notifications
Notification notification1 = new Notification();
Notification notification2 = new Notification();
// fake database of type databaseEntry in List data structure
List<databaseEntry> myDatabase = new List<databaseEntry>();
}
另一种方式是列表初始化程序。在那里,您可以避免构造函数并直接在List<T>
定义中添加项目。除了调用Add
之外,此初始化程序不起作用,但您可以直接在字段定义中使用它。
List<databaseEntry> myDatabase = new List<databaseEntry>(){
new databaseEntry() { myNotification = notification1, myStatus = "approved"},
new databaseEntry() { myNotification = notification2, myStatus = "pending"},
};