我有一個類,當我嘗試在另一個類中使用它時,我收到下面的錯誤。字段初始值設定項不能引用非靜態字段,方法或屬性
using System;
using System.Collections.Generic;
using System.Linq;
namespace MySite
{
public class Reminders
{
public Dictionary<TimeSpan, string> TimeSpanText { get; set; }
// We are setting the default values using the Costructor
public Reminders()
{
TimeSpanText.Add(TimeSpan.Zero, "None");
TimeSpanText.Add(new TimeSpan(0, 0, 5, 0), "5 minutes before");
TimeSpanText.Add(new TimeSpan(0, 0, 15, 0), "15 minutes before");
TimeSpanText.Add(new TimeSpan(0, 0, 30, 0), "30 minutes before");
TimeSpanText.Add(new TimeSpan(0, 1, 0, 0), "1 hour before");
TimeSpanText.Add(new TimeSpan(0, 2, 0, 0), "2 hours before");
TimeSpanText.Add(new TimeSpan(1, 0, 0, 0), "1 day before");
TimeSpanText.Add(new TimeSpan(2, 0, 0, 0), "2 day before");
}
}
}
另一類
class SomeOtherClass
{
private Reminders reminder = new Reminders();
// error happens on this line:
private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
....
錯誤(CS0236)使用類:
A field initializer cannot reference the nonstatic field, method, or property
它爲什麼會發生,以及如何解決它?
Java是這幾樣結構的更「寬容」。不知道這是否是件好事。 http://stackoverflow.com/questions/1494735/initialization-order-of-static-fields-in-static-class –
不,編譯器不能重新排列初始值設定項。 C#語言規範在「10.5.5.2實例字段初始化」一節中聲明如下:__變量初始值設定項按它們出現在類聲明中的文本順序執行.__甚至在「10.11.2實例變量初始值設定項「他們說:__變量初始值設定項是按它們出現在類聲明中的文本順序執行的。所以你的解釋是錯誤的。訂單是固定的。之所以被禁止是因爲C#的設計者就是這麼想的。 –
(只有在幾個文件中帶有「部分」的「partial class」的情況下,字段初始值設定項的順序不清楚,但也適用於'static'字段!) –