f# OOP -实现接口-私有和方法名称问题

本文关键字:方法 问题 OOP 实现 接口 | 更新日期: 2023-09-27 17:48:57

被一个OOP接口问题难住了。

示例-当我创建一个类,并试图实现一个方法运行(字符串,字符串,字符串)从一个接口irrunner命名空间的例子我可以看到,在。net Reflector中真正创建的是一个名为example - runner - run (string,string,string)的私有方法,如果我想把它暴露给c#库,就会出现问题。通过反射-代码我不是在控制只是寻找一个类与公共运行方法。怎么解呢?

问题1 - Run应该是公共的,但最终是私有的
问题2:方法名太长,而不是Run

不确定我是否需要使用一些修饰词关键字或签名文件....只是不只是从(1)私有和(2)奇怪的方法名(反射找不到)

开始。

注意:在这个例子中,Run返回一个int
在当前的实现中,我只是试图返回1"概念证明",我可以在f#

中做这个简单的事情

示例代码:

namespace MyRunnerLib
open Example
type MyRunner() = class
  interface IRunner with 
   member this.Run(s1, s2, s3) = 1
end

f# OOP -实现接口-私有和方法名称问题

此外,还有一些如何编写它的选项。Robert的版本在附加的成员中有实际的实现。如果将实现放在接口中,就可以避免强制类型转换。
(还要注意,你不需要class ..)end关键词):

type MyRunner() = 
  member this.Run(a,b,c) = 1
  interface IRunner with 
    member this.Run(a,b,c) = this.Run(a,b,c)

更清晰的方法是将函数定义为本地函数,然后导出两次:

type MyRunner() = 
  // Implement functionality as loal members
  let run (a, b, c) = 1
  // Export all functionality as interface & members
  member this.Run(a,b,c) = run (a, b, c)
  interface IRunner with 
    member this.Run(a,b,c) = run (a, b, c)

Euphorics答案中的第一个链接包含解决方案。作为参考,我在这里重申一下。您需要使用您感兴趣的方法在类上实现转发成员。这是因为接口在f#中是显式实现的,而在c#中默认是隐式接口实现。在你的例子中:

namespace MyRunnerLib
open Example
type MyRunner() = class
  interface IRunner with 
   member this.Run(s1, s2, s3) = 1
  member this.Run(s1, s2, s3) = (this :> IRunner).Run(s1,s2,s3)
end

在google上快速搜索第一个结果:

http://bugsquash.blogspot.com/2009/01/implementing-interfaces-in-f.htmlhttp://cs.hubfs.net/forums/thread/7579.aspx