F# OOP - Implementing an Interface - Private and Method Name Problem
Stumped with a OOP interface F# question.
Example - when I create a class and try to implement a single method Run(string,string,string) from a Namespace Example from an Interface IRunner I can see in .NET Reflector what really gets created is a private method named Example-IRunner-Run(string,string,string) If I then want to expose this back to a C# lib it presents an issue. Via reflection - code I'm not in control of is just looking for a class with a public Run method. How do I solve? Can't seem to find any documentation on this.
Problem 1 - Run should be public some how ends up private
Problem 2 - the crazy long method name - instead of just RunNot sure if I need to be using some modifier keywords or a signature file.... just not just where to start with the (1) private and (2) the strange method name (reflection won't find)
note: in this example Run returns an int
In this current implementation I'm just trying to return a 1 to "proof of concept" that I can do this simple thing in F#example code:
namespace MyRunnerLib
open Example
type MyRunner() = class
interface IRunner with
member this.Run(开发者_C百科s1, s2, s3) = 1
end
Additionally, there are a few options how to write this. Robert's version has the actual implementation in the additional member. If you place the implementation into the interface, you can avoid the casting.
(Also note that you don't need class
.. end
keywords):
type MyRunner() =
member this.Run(a,b,c) = 1
interface IRunner with
member this.Run(a,b,c) = this.Run(a,b,c)
Slightly clearer way is to define the functionality as a local function and then just export it two times:
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)
The first link in Euphorics answer contains the solution. For reference, I'll reiterate it here. You need to implement a forwarding member on your class with the method you're interested in. This is because interfaces are explicitly implemented in F# whereas in C# the default is implicit interface implementation. In your case:
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
Quick search on google and first result:
http://bugsquash.blogspot.com/2009/01/implementing-interfaces-in-f.html http://cs.hubfs.net/forums/thread/7579.aspx
精彩评论