代码之家  ›  专栏  ›  技术社区  ›  Daniel Westendorf

未知类型的方法参数

  •  -1
  • Daniel Westendorf  · 技术社区  · 8 年前

    def foo(object)
      object.public_send(:bar)
    rescue NoMethodError
      raise "Method not defined on object"
    end
    
    foo(instance_of_my_arbitrary_class)
    

    我不确定如何在Crystal中执行此操作,因为类型us未知,所以我得到了一个编译器错误 Can't infer the type of instance variable 'object' .

    2 回复  |  直到 8 年前
        1
  •  1
  •   Daniel Westendorf    8 年前

    我想我是在利用了一个模块并将其包括在内之后才发现这一点的。

    module ArbitraryObject; end
    
    class Arbitrary
      include ArbitraryObject
    end
    
    class MyLib
      def foo(object : ArbitraryObject)
        ... Code here ...
      end
    end
    
    MyLib.new(Arbitrary.new).foo
    
        2
  •  1
  •   bew    8 年前

    def foo(object)
      object.bar
    end
    
    class MyObj
      def bar
        puts "bar!"
      end
    end
    
    foo(MyObj.new) # => "bar!"
    

    在这里,它起作用了,作为 MyObj bar . 但是,如果您使用的是没有该方法的东西,则用户将获得编译时错误:

    foo(3) # compile error: undefined method 'bar' for Int32
    

    此错误将在程序执行之前显示。