class - 如何通过 "actual"类找到实例变量?

标签 class oop crystal-lang

我正在编写的程序将元素存储在名为 grid 的哈希中,其类型为 Position => LivingBeing |事情。此网格存储在Map上,我希望此Map返回Apple类元素的位置> 它是 Thing 的子类。

但是,当使用 typeof() 获取类时,我得到 LivingBeing | Thing 而不是子类 Apple

这是Map类:

class Map
  @@grid = {} of Position => LivingBeing | Thing

  def initialize()
  end

  # Add an entity to the grid
  def add_entity(new_entity : LivingBeing | Thing)
    @@grid[new_entity.position] = new_entity
  end

  # Return the position of an object of class "something"
  def self.where_is?(something : Class)
    # First attempt was to get the key by the value
    # @@grid.key(something)

    @@grid.each do |position, thing|
      # Returns "thing #<Apple:0x55f1772085c0> at Position(@x=1, @y=2) is (LivingBeing | Thing)"
      puts "thing #{thing} at #{position} is #{typeof(thing)}"
      position if typeof(thing) == something
    end
  end

这里是 Thing 类:

abstract class Thing
  getter position
  @name = "Unkown object"

  def initialize(@position : Position)
  end
end

class Apple < Thing
  @name = "Apple"
end

这里是Position结构:

struct Position
  getter x, y

  def initialize(@x : Int32, @y : Int32)
  end
end

这是我试图让它通过的测试:

it "gives a random thing location based on its class" do
  world = Map.new()
  apple = Apple.new(Position.new(1, 2))
  puts "Apple type : #{typeof(apple)}" # Returns "Apple type : Apple"
  world.add_entity(apple)
  position = Map.where_is?(Apple)
  position.should eq Position.new(1, 2)
end

是否有一些类方法或函数可以提供 Apple 类? 还是设计问题?

谢谢您的回答!

最佳答案

您可以使用forall来解决这个问题:

  # Return the position of an object of class "something"
  def self.where_is?(something : T.class) forall T
    @@grid.each do |position, thing|
      return position if thing.is_a?(T)
    end
  end

并使用Map.where_is? 调用它苹果正如你所愿。

这是可行的,因为类型变量 T(使用 forall T 引入)可以通过传入常量 推断为 Apple >Apple 匹配 T.class 类型限制。 T 是一个常量,可以与 is_a? 一起使用。

关于class - 如何通过 "actual"类找到实例变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47982006/

相关文章:

java - 如何解决无法在 Maven 项目中内省(introspection)测试类的警告?

JavaScript 类表示法和 'this' 关键字

php - 什么时候在 PHP 中使用 Final?

c++ - 如何在继承类成员函数中访问基类成员的地址?

java - 如何在 Java 程序中通过 java.net.URL 类监控打开的 URL?

c++ - 在构造函数中调用纯虚函数会报错

iphone - 试图给另一个类(class)的按钮发消息

crystal-lang - 从 stdin 读取单个字符而不按 Enter

user-interface - Crystal native GUI

random - 如何在 Crystal 中生成随机数?