亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

字段初始化程序不能引用非靜態字段、方法或屬性。

字段初始化程序不能引用非靜態字段、方法或屬性。

C#
LEATH 2019-06-25 15:02:28
字段初始化程序不能引用非靜態字段、方法或屬性。我有一個類,當我嘗試在另一個類中使用它時,我會收到下面的錯誤。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)];}

原因是不能使用一個實例變量來使用字段初始化器初始化另一個實例變量,因為字段初始化程序的執行順序是未定義的。


查看完整回答
反對 回復 2019-06-25
?
慕森王

TA貢獻1777條經驗 獲得超3個贊

你可以這樣用

private dynamic defaultReminder => reminder.TimeSpanText[TimeSpan.FromMinutes(15)];


查看完整回答
反對 回復 2019-06-25
  • 3 回答
  • 0 關注
  • 845 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號