无法全面了解与QUOT; A字段初始不能引用非静态场"错误? [英] Unable to understand "A field initializer cannot reference the nonstatic field" Error?

查看:174
本文介绍了无法全面了解与QUOT; A字段初始不能引用非静态场"错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到错误一个字段初始不能引用非静态场,而我的code是如下:

I am getting the error "A field initializer cannot reference the nonstatic field", While My code is as below:

Object selectedItem = PageVariables.slectedItemData;
MyClass selectedItems = (MyClass)selectedItem;

但是,如果在该构造中或在不同的方法分配的值,同样的事情的工作方式类似如下:

But the same thing works if assign the value at the constructor or in a different method , like below:

public partial class MusicPlayer : Page
{
   Object selectedItem = PageVariables.slectedItemData;
    public MusicPlayer()
      {
        InitializeComponent();
        MyClass selectedItems = (MyClass)selectedItem;
      }
}

我只是想了解有什么不同,为什么它正在寻找一个静态varaible声明(在第一种情况),而不会寻找它,而在构造函数或不同的方法!

I am just trying to understand what is the difference, Why it is looking for a static varaible declaration(in 1st case) while doesn't look for it while in a constructor or a different method!!!

推荐答案

是不是因为作为一个字段使用时动初始化的顺序没有定义,即selectedItems可以将selectedItem前初始化,这将导致一个错误(或者至少在意外的行为,这selectedItems为null)。在第二个例子中的顺序是专用的,所以一切都是虎背熊腰,脚蹬dory没问题。

isn't it because the order of initilization when used as a field is not defined, ie selectedItems could be initialized before selectedItem, which would result in an error (or at least in unexpected behaviour, that selectedItems was null). In the second example the order is specific so everything is hunky dory.

这篇关于无法全面了解与QUOT; A字段初始不能引用非静态场"错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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