我有一個存儲庫類和服務類如下:字段初始值設定項無法引用非靜態字段,方法或屬性?
public class DinnerRepository
{
DinnerDataContext db = new DinnerDataContext();
public Dinner GetDinner(int id)
{
return db.Dinners.SingleOrDefault(d => d.DinnerID == id);
}
// Others Code
}
public class Service
{
DinnerRepository repo = new DinnerRepository();
Dinner dinner = repo.GetDinner(5);
// Other Code
}
這將引發錯誤:
A field initializer cannot reference the non-static field, method, or property.
儘管我已經intatiated的DinnerRepository類在服務揭露其方法GetDinner()類。這適用於下面的代碼。除此之外還有其他選擇嗎?還是標準做法?我不能在這裏使用靜態方法..
public class Service
{
public Service()
{
DinnerRepository repo = new DinnerRepository();
Dinner dinner = repo.GetDinner(5);
}
}
是的,現在的版本是這樣的:「因爲我們在'simple-name's上有編譯時錯誤,所以我們引用'this'是一個錯誤」,而不是其他方式。 – SWeko
@JonSkeet這種行爲的原因是字段在構造函數之前被初始化。所以當你嘗試初始化字段時沒有實例成員。這就是爲什麼你不能在課堂實例化之前使用它們吧? – UfukSURMEN
@UfukSURMEN:不是真的......對象已經存在,但它會引起一些相當難以理解的錯誤。 (有時候這很煩人,無可否認......) –