我需要从一个班级到另一个班级。但是我仍然遇到这个错误。
“字段初始值设定项不能引用非静态字段,方法或属性”
我读到我必须得到构造函数的smth,但是没有任何作用。
提前感谢!
namespace NovejKalendar
{
class Program
{
static void Main(string[] args)
{
Calendar c = new Calendar();
Day d = new Day();
c.AddRecord();
c.Print();
//Day d = new Day();
Console.ReadKey(true);
}
}
class Homework
{
public DateTime dt;
public string subject;
public string content;
public Homework(DateTime dt, string subject, string content)
{
String.Format("{0:d.m.yyyy HH:mm}", dt);
//String.Format("{0:d/M/yyyy HH:mm:ss}", dt); // "9.3.2008 16:05:07"
this.dt = dt;
this.subject = subject;
this.content = content;
}
}
class Day
{
List<Homework> hw = new List<Homework>();
public List<Homework> GetList()
{
hw = new List<Homework>();
return hw;
}
}
class Calendar
{
//List<Homework> hw = new List<Homework>();
Day d = new Day();
List<Homework> hw = d.GetList();
//List<Homework> hw = new List<Homework>();
public void AddRecord()
{
string a = "9.3.2008 16:05";
string b = "19.12.2009 16:40";
string c = "29.5.2005 16:55";
hw.Add(new Homework(Convert.ToDateTime(a), "M", "ONE"));
hw.Add(new Homework(Convert.ToDateTime(b), "F", "TWO"));
hw.Add(new Homework(Convert.ToDateTime(c), "INF", "THREE"));
}
public void PrintCollection<T>(IEnumerable<T> col)
{
foreach (var a in col)
Console.WriteLine(hw);
}
public void Print()
{
foreach (var p in hw)
{
Console.WriteLine("{0} {1} {2}", p.dt, p.subject, p.content);
}
}
}
}
答案 0 :(得分:0)
您无法像这样直接初始化字段:
List<Homework> hw = d.GetList();
相反,只需定义变量并在类构造函数中初始化它。
class Calendar
{
List<Homework> hw;
public Calendar()
{
hw = d.GetList();
}
...
}
错误消息很清楚..
&#34;字段初始值设定项不能引用非静态字段,方法, 或财产&#34;