Unable to understand "A field initializer cannot reference the nonstatic field" Error?
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;
}
}
I am just trying to understand what is the difference, Wh开发者_C百科y 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!!!
It isn't the static field that's the problem. It's the attempt to use the non-static field selectedItem
in the initialization of another non-static field selectedItems
. This is a restriction in C#.
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.
That restriction (A field initializer cannot reference the nonstatic field) is related to the fact that field initializers run before constructors. (From derived to base and then all constructors from base to derived)
精彩评论