不同命名空间中的 AS3 Getter 和同伴 setter

发布于 2024-12-08 23:49:03 字数 519 浏览 0 评论 0原文

我正在尝试创建一个可以通过公开扩展类和读取设置的属性。

我想不出一个带有 public getter 的 protected 属性的良好命名约定,所以我尝试这样做:

public function get name():String{ return _name; }
protected function set name(string:String):void
{
    _name = string;
}

但是我收到错误(当尝试 < code>set name 在扩展类中):

1178:尝试通过访问无法访问的属性名称 静态类型测试参考:TestComponent.

1059: 属性是只读的。

如果我将设置器更改为 public,它就可以正常工作。

I'm trying to create a property that can be set by extending classed and read publicly.

I couldn't think of a good naming convention for a protected property with a public getter, so I tried to do this:

public function get name():String{ return _name; }
protected function set name(string:String):void
{
    _name = string;
}

However I get the error (when trying to set name in an extending class):

1178: Attempted access of inaccessible property name through a
reference with static type testing:TestComponent.

1059: Property is read-only.

If I change the setter to public, it works fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

并安 2024-12-15 23:49:03

据我所知,AS3 不允许混合和匹配,两个访问器应该是相同的。

我通常不提供 setter 来使属性只读,而是直接在内部设置 _name 。因为它受到保护,所以后代可以访问它。

As far as I know AS3 doesn't allow you to mix and match, both accessors should be the same.

I generally don't supply a setter to make the property read only, and directly set _name internally. Because it's protected, it will be accessible to descendants.

烟柳画桥 2024-12-15 23:49:03

您可以像下面这样使用它。

public class Test extends Object {
    protected var _name:String;
    public function get name():String {return _name;}
}

public class Test2 extends Test {
    public function set name(s:String):void {
        this._name = s;
    }
}

You can use it like below.

public class Test extends Object {
    protected var _name:String;
    public function get name():String {return _name;}
}

public class Test2 extends Test {
    public function set name(s:String):void {
        this._name = s;
    }
}
沉溺在你眼里的海 2024-12-15 23:49:03

我采取了稍微不同的方法来实现我想要的:

public function get name():String{ return _name; }
public function set name(string:String):void
{
    if(!_name.length)
        _name = string;

    else throw new Error("Property \"name\" can only be defined once.");
}

现在 name 将在扩展类中定义,但从那时起就无法设置。

I took a slightly different approach to achieve what I wanted:

public function get name():String{ return _name; }
public function set name(string:String):void
{
    if(!_name.length)
        _name = string;

    else throw new Error("Property \"name\" can only be defined once.");
}

Now name will be defined within the extending class, but can't be set from then on.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文