[英]F# OOP - Implementing an Interface - Private and Method Name Problem
陷入OOP接口F#问题。
示例-当我创建一个类并尝试从名称空间实现单个方法Run(string,string,string)时,它来自接口IRunner我可以在.NET Reflector中看到真正创建的是一个名为Example-IRunner-的私有方法Run(string,string,string)如果然后我想将此内容公开给C#库,则会出现问题。 通过反射-我无法控制的代码只是在寻找带有公共Run方法的类。 我该如何解决? 似乎找不到任何相关文档。
问题1-跑步应该是公开的,如何最终变成私有的
问题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
此外,还有一些如何编写此代码的选项。 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)
欣快感答案中的第一个链接包含解决方案。 作为参考,我将在这里重申。 您需要使用您感兴趣的方法在类上实现转发成员。这是因为接口是在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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.