字段初始化程序不能引用非静态字段、方法或属性。我有一个类,当我尝试在另一个类中使用它时,我会收到下面的错误。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)];
....错误(CS 0236):A field initializer cannot reference the nonstatic field, method, or property为什么会发生这种情况,以及如何解决?
3 回答
慕田峪4524236
TA贡献1875条经验 获得超5个赞
private Reminders reminder = new Reminders();private dynamic defaultReminder;public YourClass(){ defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];}
慕森王
TA贡献1777条经验 获得超3个赞
private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
- 3 回答
- 0 关注
- 817 浏览
添加回答
举报
0/150
提交
取消