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

问题描述

我有一堂课

public class LED
{
    public System.Windows.Forms.Label lbl;

    public LED(System.Windows.Forms.Label lblLED)
    {
        lbl = lblLED;
    }

    public void blink(System.Drawing.Color color, int pattern)
    {
        // ...
    }
}

并且我正在顶级创建它的实例:

and I'm creating an instance of it in a top-class:

    public LED LED1 = new LED(lblLED1); // (1)

    public void update_LED(Label lbl, double i)
    {
        //LED LED1 = new LED(lblLED1); // (2)
    }

在情况(2)中,它允许我在构造函数中传递lblLED1,但在情况(1)中,它说:

in case (2) it allows me to pass lblLED1 inside the constructor, but in case (1) it says:

出什么问题了?

推荐答案

http://msdn.microsoft.com/en-us/library/5724t6za%28VS.80%29.aspx

您不能使用对字段的引用来初始化方法外部同一类中的字段,这可能是因为不能保证引用变量的初始化顺序.

you cant use references to fields to initialize fields in the same class outside of a method, maybe because the order in which the reference variables are initialized is not guaranteed.

这篇关于字段初始化程序无法引用非静态字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:06