Hi ritcoder,

Looks like you need a bit of reflection here, though reflection should normally be used only if there isn't a more functional, verifiable method available. This should do the trick for most simple classes:

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
let fill inst (kvps : Map<string, string>) =
    let props = inst.GetType().GetProperties()
    for prop in props do
        let name = prop.Name
        if kvps.ContainsKey(name) then
            match prop.GetValue(inst, null) with
            | :? string -> prop.SetValue(inst, string kvps.[name], [| |] )
            | :? int64  -> prop.SetValue(inst, System.Int64.Parse( kvps.[name] ), [| |] )
            | _         -> () // Fill further cases as require. 


// Interactive
> val fill : 'a -> Map<string,string> -> unit


type Person = 
    { mutable Name: string; mutable Desc: string; mutable Index: int64 }
    static member New = {Name = ""; Desc = ""; Index = 0L}


let bob = [ ("Name", "Bob") ; ("Desc", "Builder") ; ("Index", "101") ]
          |> Map.of_list


let newguy = Person.New


newguy;;
> val it : Person = {Name = "";
                     Desc = "";
                     Index = 0L;}
 

bob |> fill newguy


newguy;;
> val it : Person = {Name = "Bob";
                     Desc = "Builder";
                     Index = 101L;}

regards,

Danny

By on 1/15/2009 9:27 AM ()

Hi,
Thanks for the response. That was very close to what I was looking for. I just made the conversion use a function called cast.

let cast (typ:Type) src = Convert.ChangeType (src ,typ)

One quick question:
Is it possible to change the definition of cast as it is to have a return type of type typ?

eg
let cast2 src sample=
let typ = sample.GetType()
let ret = cast (typeof<'T>) src
ret :?> typ // this will not compile

The original problem is solved though. thank you.

By on 1/15/2009 12:50 PM ()
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