2011-04-07 58 views
2

难以置信的OOP接口F#问题。F#OOP - 实现接口 - 私有和方法名称问题

示例 - 当我创建一个类并尝试实现单个方法从命名空间运行(字符串,字符串,字符串)从接口IRunner示例 我可以在.NET Reflector中看到真正创建的是私有方法命名为Example-IRunner-Run(字符串,字符串,字符串)如果我然后想公开这个回到C#lib它提出了一个问题。通过反射 - 我无法控制的代码只是使用公共Run方法寻找一个类。我如何解决?似乎无法找到关于此的任何文档。

问题1 - 运行应该是公开的一些如何结束了私人
问题2 - 疯狂长的方法名 - 而不是只运行

不知道如果我需要使用一些修改关键字或签名文件....(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 

回答

3

此外,有几个选项如何写这个。 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) 
1

在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