字段初始不能引用非静态字段,方法或属性 [英] A field initializer cannot reference the nonstatic field, method, or property

查看:173
本文介绍了字段初始不能引用非静态字段,方法或属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类,当我尝试在其他类中使用它,我收到以下错误。

I have a class and when I try to use it in another class I receive the error below.

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):

Error (CS0236):

A field initializer cannot reference the nonstatic field, method, or property

它为什么会发生,以及如何解决它?

Why does it happen and how to fix it?

推荐答案

这行:

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

您不能使用实例变量初始化的其他的实例变量。为什么?因为编译器可以重新安排这些 - 不保证是提醒将在 defaultReminder 初始化,所以上面的行可能的抛出一个的NullReferenceException

You cannot use an instance variable to initialize another instance variable. Why? Because the compiler can rearrange these - there is no guarantee that reminder will be initialized before defaultReminder, so the above line might throw a NullReferenceException.

相反,只需使用:

private dynamic defaultReminder = TimeSpan.FromMinutes(15);

另外,在构造函数中设置的值:

Alternatively, set up the value in the constructor:

private dynamic defaultReminder;

public Reminders()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; 
}

有关于MSDN此编译器错误的详细信息 - 编译器错误CS0236

There are more details about this compiler error on MSDN - Compiler Error CS0236.

这篇关于字段初始不能引用非静态字段,方法或属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆