原文出处:https://blog.csdn.net/honey199396/article/details/79539877
TypeScript语法请看TypeScript中文网
这里我们主要是看一下存取器,也就是get,set方法。

在C#中,我们使用存取器的方法是

public int m_Life = 0;
    public int Life
    {
        get
        {
            return m_Life;
        }

        set
        {
            m_Life = value;
        }
    }

而在TypeScript中用法如下:

class Person {
    constructor() {
    }
    private _name: string;

    public get name() {
        return this._name;
    }

    public set name(name: string) {
        this._name = name;
    }
}

let person = new Person();

// person._name = "apple";  // 无法访问到_name变量

person.name = "apple";

console.log(person.name);  // 输出 apple

虽然写起来比较麻烦,但是用起来还是很方便的。


本文转载:CSDN博客