代码之家  ›  专栏  ›  技术社区  ›  Aliaksandr Sushkevich

我可以在racket类中定义静态字段吗?

  •  2
  • Aliaksandr Sushkevich  · 技术社区  · 6 年前

    我找不到一种方法来定义球拍中的静态场。静态是指属于整个类而不是实例的字段。

    (define counter% (class object%  
      (field (current-count 0))
      (super-new)
    
      (define/public (get-count)
        current-count)
    
      (define/public (next) 
        (set! current-count (+ current-count 1))
        (set! total (+ total 1))
        (list current-count total))))
    
    (define c1 (new counter%))
    (define c2 (new counter%))
    
    (send c1 next)
    (send c1 next)
    (send c1 next)
    (send c2 next)
    

    total 在本例中,应为静态字段,输出应为:

    '(1 1)
    '(2 2)
    '(3 3)
    '(1 4)
    
    1 回复  |  直到 6 年前
        1
  •  2
  •   soegaard    6 年前

    #lang racket
    
    (define counter%
      (let ([total 0])
        (class object%  
          (field (current-count 0))
          (super-new)
    
          (define/public (get-count)
            current-count)
    
          (define/public (next) 
            (set! current-count (+ current-count 1))
            (set! total (+ total 1))
            (list current-count total)))))
    
    (define c1 (new counter%))
    (define c2 (new counter%))
    
    (send c1 next)
    (send c1 next)
    (send c1 next)
    (send c2 next)