Define an interface that inherits from both of the desired interfaces; you can then easily create an object expression from that:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#light
type IA =
   interface
      abstract a : unit -> int
   end

type IC =
   interface
      abstract b : unit -> int;
   end

type IAC =
    inherit IA
    inherit IC

let x = { new IAC with
        member x.b () = 2 
        member x.a () = 4 
        }

let pam a msg = printfn "%A = %s" a msg
pam (x.a()) "x.a()"

printf "----- Press any key. -----"
System.Console.ReadKey(false) |> ignore

~TMSteve

By on 4/6/2008 12:59 AM ()

There's a couple of things your doing wrong. You need to use :?> instread of :>. :> means downcast, a cast that can always work (i.e. going from string to obj). :?> is an upcast, a cast that may fail (i.e. obj to string). Also you need to box x before this cast, F# seems to assume that if a type is anything other than obj it can not be cast to an interface. Perphas this limitation could be removed, but I'm not sure. An easier way it to access the members via pattern matching. I've shown this in the fixed version of the code below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#light
type IA =
   abstract a : unit -> int

type IC =
    abstract b : unit -> int;

let x = { new IC with
            member x.b () = 2 
          interface IA with 
            member x.a () = 4 }

x.b()

((box x) :?> IA).a() 

let acessMembers x =
  match box x with
  | :? IC as x -> x.b()
  | :? IA as x -> x.a()
  | _ -> 0
By on 4/5/2008 9:36 PM ()

Submitted a bug report about (x :?> IA) producing a compile error, Don confirmed it has already been fixed and will be available in a future release.

Cheers,
Rob

By on 4/6/2008 3:06 AM ()
IntelliFactory Offices Copyright (c) 2011-2012 IntelliFactory. All rights reserved.
Home | Products | Consulting | Trainings | Blogs | Jobs | Contact Us | Terms of Use | Privacy Policy | Cookie Policy
Built with WebSharper