f#types的属性顺序不一致,类型略有不同

时间:2010-06-08 17:41:26

标签: reflection f# recursion

我正在尝试遍历一个对象数组并递归打印出每个对象属性 这是我的对象模型:

type firmIdentifier = {
    firmId: int ;
    firmName: string ;
}
type authorIdentifier = {
    authorId: int ;
    authorName: string ;
    firm: firmIdentifier ;
}

type denormalizedSuggestedTradeRecommendations = {
    id: int ; 
    ticker: string ;
    direction: string ;
    author: authorIdentifier ;
}

以下是我实例化对象的方法:

let getMyIdeasIdeas = [|
     {id=1; ticker="msfqt"; direction="buy"; 
        author={authorId=0; authorName="john Smith"; firm={firmId=12; firmName="Firm1"}};};

     {id=2; ticker="goog"; direction="sell"; 
        author={authorId=1; authorName="Bill Jones"; firm={firmId=13; firmName="ABC Financial"}};};

     {id=3; ticker="DFHF"; direction="buy"; 
        author={authorId=2; authorName="Ron James"; firm={firmId=2; firmName="DEFFirm"}};}|]

这是我的迭代,递归和打印算法:

let rec recurseObj  (sb : StringBuilder) o=
            let props : PropertyInfo [] = o.GetType().GetProperties()
            sb.Append( o.GetType().ToString()) |> ignore
            for x in props do
                let getMethod = x.GetGetMethod()
                let value = getMethod.Invoke(o, Array.empty)
                ignore <|
                        match value with
                        | :? float  | :? int | :? string | :? bool as f -> sb.Append(x.Name + ": " + f.ToString() + "," ) |> ignore
                        | _ ->  recurseObj  sb value
 for x in getMyIdeas do
                recurseObj sb x
                sb.Append("\r\n") |> ignore

如果你不知道,我正在尝试创建一个csv文件并打印出类型以进行调试。问题是,第一个元素按照你期望的顺序出现,但是所有后续元素都会以“child”属性的略微不同(并且令人困惑)排序,如下所示:

  

RpcMethods + denormalizedSuggestedTradeRecommendationsid:   1,股票代码:msfqt,方向:   买,RpcMethods + authorIdentifierauthorId:   0,authorName:约翰   史密斯,RpcMethods + firmIdentifierfi​​rmId:   12,firmName:Firm1,

     

RpcMethods + denormalizedSuggestedTradeRecommendationsid:   2,自动收报机:goog,方向:   销售,RpcMethods + authorIdentifierauthorName:   法案   琼斯,RpcMethods + firmIdentifierfi​​rmName:   ABC Financial,firmId:13,authorId:1,

     

RpcMethods + denormalizedSuggestedTradeRecommendationsid:   3,股票代码:DFHF,方向:   买,RpcMethods + authorIdentifierauthorName:   罗恩   詹姆斯,RpcMethods + firmIdentifierfi​​rmName:   DEFFirm,firmId:2,authorId:2,

知道这里发生了什么吗?

2 个答案:

答案 0 :(得分:1)

添加此帮助吗?

        for x in props |> Array.sortBy (fun p -> p.Name) do 
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

一般来说,我认为反射以未指定的顺序返回实体(如属性,方法,属性)。那么只需选择一个固定的排序顺序?

(或者我误解了这个问题?)

答案 1 :(得分:0)

这是一个反思的事情。您不能使用反射依赖属性的顺序。我需要使用MetaTokens进行排序。当我开始实施它时,我会发布这个解决方案。