被 OOP 接口(interface) F# 问题难住了。
示例 - 当我创建一个类并尝试从接口(interface) IRunner 的命名空间示例实现单个方法 Run(string,string,string) 时 我可以看到在 .NET Reflector 中真正创建的是一个名为 Example-IRunner-Run(string,string,string) 的私有(private)方法,如果我随后想将其公开给 C# 库,则会出现问题。通过反射 - 我无法控制的代码只是寻找具有公共(public) Run 方法的类。我该如何解决?似乎找不到任何相关文档。
问题 1 - 运行应该是公开的,但最终却变成了私有(private)
问题 2 - 疯狂的长方法名称 - 而不仅仅是 Run
不确定我是否需要使用一些修饰符关键字或签名文件......不仅仅是从哪里开始(1)私有(private)和(2)奇怪的方法名称(反射找不到)
注意:在此示例中,Run 返回一个 int
在当前的实现中,我只是尝试将 1 返回到“概念证明”,我可以在 F# 中完成这个简单的事情
示例代码:
namespace MyRunnerLib
open Example
type MyRunner() = class
interface IRunner with
member this.Run(s1, s2, s3) = 1
end
最佳答案
此外,还有一些如何编写此代码的选项。罗伯特的版本在附加成员中有实际的实现。如果将实现放入接口(interface)中,则可以避免强制转换。
(另请注意,您不需要 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)
关于c# - F# OOP - 实现接口(interface) - 私有(private)和方法名称问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5576276/