且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

实例成员不能用于Class类型吗?

更新时间:2022-11-19 20:55:02

您不能直接在静态方法中访问非静态内容.

You cannot access non-static stuff directly in a static method.

方法letKnowPersonDeinitialized是静态的,因为它已使用static修饰符进行了修改:

The method letKnowPersonDeinitialized is static because it is modified with the static modifier:

static func letKnowPersonDeinitialized() {
  ^
  |
here!
}

Personname属性不是静态的,因为它没有被static修改.

The name property of Person is not static because it is not modified by static.

由于非静态成员属于该类的每个单独实例,而静态成员属于该类本身,因此静态成员无法直接访问非静态成员.他们只能在存在实例的情况下访问非静态成员.

Since non-static members belong to each individual instance of that class and static members belong to the class itself, static members have no direct access to non-static members. They can only access non-static members when an instance is present.

要解决您的问题,请在letKnowPersonDeinitialized方法中添加一个参数:

To solve your problem, add a parameter to the letKnowPersonDeinitialized method:

static func letKnowPersonDeinitialized(person: Person) {
    print(person.name)
}

然后在反初始化器中:

deinit {
    Indicator.letKnowPersonDeinitialized(self)
}


非常重要的东西:

我认为您的代码设计得不好.这不是您使用继承的方式.


VERY IMPORTANT STUFF:

I don't think your code is designed well. This is not how you use inheritance.

继承表示是一种".因此,如果Indicator继承自Person,则意味着指标是一种人.

Inheritance means "is a kind of". So if Indicator inherits from Person, it means that an indicator is a kind of person.

根据常识,指标不是人.因此,此处不适合使用继承.没什么意义.

According to common sense, an indicator is not a person. Therefore, it is not suitable to use inheritance here. It makes little sense.