【问题标题】:How to compare objects in Vala?如何比较 Vala 中的对象?
【发布时间】:2016-05-10 02:06:17
【问题描述】:

我正在使用带有自己的内容类的 Gee.ArrayList。我想使用 ArrayList 的“包含”方法,但我真的不知道如何在我的类中设置 equals 方法,因此 ArrayList 使用它来确定对象是否在 ArrayList 中。

例子:

class Test : GLib.Object {
    public int number;
    
    public Test(int n) {
        number = n;
    }
    public bool equals (Test other) {
        if (number == other.number) return true;
        return false;
    }
}

然后,在另一个文件中:

var t = new Gee.ArrayList<Test>();
var n1 = new Test(3);
var n2 = new Test(3);
t.add(n1);
t.contains(n2); // returns false, but I want it to return true

有人知道吗?

【问题讨论】:

    标签: vala libgee


    【解决方案1】:

    当您创建 ArrayList 时,constructor 将获取您的相等比较器。你可以这样做:

    var t = new Gee.ArrayList<Test>(Test.equals);
    

    并且包含应该可以按您的意愿工作。

    【讨论】:

    • 谢谢!实际上,您必须将 Test.equals 转换为 EqualFunc: var t = new Gee.ArrayList((EqualFunc) Test.equals) 做到了! :-)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多