如何申报字段?

时间:2016-05-08 10:26:50

标签: scope gtk vala

我在Vala中编写了一个GUI程序。当我编译它时,编译器会产生这个错误:

The name e1 does not exist in the context of Subtract.minus  

代码是:

using Gtk;
class Subtract:Window{
    public Subtract(){
        this.title="Subtract program";
        this.destroy.connect(Gtk.main_quit);
        var e1=new Entry();
        var e2=new Entry();
        var lbl=new Label("Result");
        var btn=new Button.with_label("Subtract");
        var box=new Box(Gtk.Orientation.VERTICAL,5);
        box.add(e1);
        box.add(e2);
        box.add(lbl);
        box.add(btn);
        this.add(box);
        btn.clicked.connect(minus);
    }
    public void minus(){
        int a=int.parse(e1.get_text());
        int b=int.parse(e2.get_text());
        int result=a-b;
        lbl.set_label(result.to_string());
    }
    public static int main(string[]args){
        Gtk.init(ref args);
        var win=new Subtract();
        win.show_all();
        Gtk.main();
        return 0;
    }
}

如何通过minus方法访问变量。

1 个答案:

答案 0 :(得分:1)

您必须将小部件的变量(至少e1e2lbl)声明为字段:

using Gtk;

class Subtract: Window {

    // Fields (sometimes also called "attributes")
    private Entry e1;
    private Entry e2;
    private Label lbl;
    private Button btn;
    private Box box;

    public Subtract () {
        title = "Subtract program";
        destroy.connect (Gtk.main_quit);
        // You don't have to use "this." to access fields in Vala
        // I.e. "this.e1" is equivalent to "e1" in the code below
        e1 = new Entry ();
        e2 = new Entry ();
        lbl = new Label ("Result");
        btn = new Button.with_label ("Subtract");
        box = new Box (Gtk.Orientation.VERTICAL, 5);
        box.add (e1);
        box.add (e2);
        box.add (lbl);
        box.add (btn);
        add (box);
        btn.clicked.connect (minus);
    }

    public void minus () {
        // The compiler happily accepts "e1" (etc.) here now
        // since I have declared them as fields
        int a = int.parse (e1.get_text ());
        int b = int.parse (e2.get_text ());
        int result = a - b;
        lbl.set_label (result.to_string ());
    }

    public static int main (string[] args) {
        Gtk.init (ref args);
        var win = new Subtract ();
        win.show_all ();
        Gtk.main ();
        return 0;
    }
}

PS:正确的技术术语是“范围”。你的代码在构造函数的范围内有变量,我的代码作为类作用域的变量,这使得它们在类的所有方法中都可见。

Vala编译器将其称为“上下文”,在这种情况下大致相同。