【问题标题】:Genie's writeonly propertyGenie 的只写属性
【发布时间】:2016-04-28 14:27:19
【问题描述】:

我从vala tutorial读到的

只读:vala

public int b { get; private set; }

在精灵中:

prop readonly b: int

只写: 瓦拉:

public int b { private get; set; }

精灵:[这一行:语法错误]

prop writeonly b: int

如何在 Genie 中声明一个 单行 writeonly 属性? 也许是这样的?

prop XXX b: int

我们可以写一个四行 writeonly 属性:

class Wonly
    _b: int
    prop b: int
        set
            _b = value

init
    var w = new Wonly
    // print w.b // ERROR!! writeonly!!
    w.b = 456   // OK

但是如何写一个单行的 writeonly 属性呢?

【问题讨论】:

  • 我明白你现在想要什么了,似乎不可能有一个单行 writeonly 属性定义。但是不要相信我的话,因为我真的开始学习这门语言了。希望其他人可以加入来解决您的问题。让我们拭目以待。

标签: class properties genie


【解决方案1】:

我会尽力在这里回答您的问题,但是您的问题的某些方面并不清楚。也许提供更多上下文会有所帮助,更好地解释您计划实现的目标以及更多用于上下文化的代码。

也就是说,我假设您询问的是 Genie 中类属性的语法。

属性是向您开发的类的用户隐藏实现细节的方法。根据 Vala 的tutorial,这一举措在计算机科学中也称为information hiding principle

在 Vala 中,属性将按以下方式在 a 中定义:

static int current_year = 2525;
class Person : Object {
    private int year_of_birth = 2493;

    public int age {
        get { return current_year - year_of_birth; }
        set { year_of_birth = current_year - value; }
    }
}

在 Genie 中,它看起来像这样:

class Foo : Object

    prop name : string

    prop readonly count : int

    [Description(nick="output property", blurb="This is the output property of the Foo class")]    
    prop output : string
        get
            return "output"
        set
            _name = value

现在是只写属性。基于 SO 的thisthis 问题,这是一个有争议的问题。只有当您不打算阅读您所写的内容时,它似乎才有用。但是正如您在上面的问题中看到的那样,大多数答案都建议创建方法而不是使用只写属性。

这将我们带到您指向的语法:

public int b { private get; set; } 

你说这是 Vala 中只写属性的语法,这似乎是真的。这是因为,通过将 get 设置为私有,您可以防止用户读取该值。您也可以将 get 或 set 设置为在 Vala 中的私有,方法是将其排除在 set 块之外,即在 Vala 中您可以简单地删除 private get 部分。

现在这是我不确定的地方,但我建议您在代码中尝试一下。基于 Vala 通过从 set 块中删除它们来设置私有 getter 或 setter 的能力,我怀疑这同样适用于 Genie。

我从以下代码中删除了 get 的设置并编译:

[indent=4]

class Foo : Object

    prop name : string

    prop readonly count : int

    [Description(nick="output property", blurb="This is the output property of the Foo class")]
    prop output : string
        set
            _name = value

init
    var foo = new Foo()

也许这就是您正在寻找的东西,但我不确定它是否可以在实际代码中工作。如果没有,也许你最好用方法代替。

【讨论】:

  • 对不起!路易斯,我的问题没有解决!,我已经更新了!。
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 2011-05-15
  • 2011-07-20
  • 2010-12-02
  • 2011-06-23
  • 2014-10-20
  • 1970-01-01
  • 2011-01-13
相关资源
最近更新 更多