4

我正在尝试实现一个具有属性但似乎无法使其正常工作的接口,而且我还没有通过 Google 找到任何相关示例(还)。我确定我在这里做错了,但不知道如何解决。

(System.Reflection.Assembly/LoadWithPartialName "System.Web")

; naive, just trying to figure out how to implement the IHttpHandler interface in Clojure 
(defn foo-handler []
    (reify System.Web.IHttpHandler
        (IsReusable [] false)
        (ProcessRequest [context] ())))

IsReusable 是一个属性,我不知道如何告诉 reify 它不是一个传统的函数。

CompilerException clojure.lang.CljCompiler.Ast.ParseException: Must supply at least one argument for 'this' in: IsReusable

好的,我为 IsReusable 提供“this”

CompilerException clojure.lang.CljCompiler.Ast.ParseException: Can't define method not in interfaces: IsReusable

我也尝试过代理,但我得到了类似的结果。

我还尝试将 IsReusable 命名为 get_IsReusable ,这实际上并没有什么不同,并且我得到了与上面相同的编译器错误。

我也试过 deftype 但我得到一个完全不同的错误:

(deftype foo-handler []
  System.Web.IHttpHandler
  (get_IsReusable [this] false)
  (ProcessRequest [this context] ()))

编译器错误:

InvalidCastException Unable to cast object of type 'clojure.lang.Var' to type 'System.Type'.  clojure.lang.Namespace.ReferenceClass 

更新:

为 deftype 发布的代码有效,我无法重现上面发布的错误。我现在不知道我当时做错了什么。

4

1 回答 1

10

这花了我几个小时的研究和反复试验,但我终于成功了!

user=> (def foo-handler
(reify System.Web.IHttpHandler
        (get_IsReusable [this] false)
        (ProcessRequest [this context] ())))
#'user/foo-handler
user=>

成功!

user=> (instance? System.Web.IHttpHandler foo-handler)
true

这种方式更好,并且可以在 ASP.NET 应用程序中正常工作:

(deftype foo-handler []
  System.Web.IHttpHandler
  (get_IsReusable [this] false)
  (ProcessRequest [this context] 
    (.Write (.Response context) "Hello, From Clojure CLR!")))
于 2013-12-09T17:56:48.863 回答