2012-10-17 61 views
2

我目前正在嘗試SqlDataConnection類型的提供程序,並想知道如何顯示這些類型。F#類型提供商打印

有什麼方法可以讓我打電話給printfn "%A"顯示比類型名稱更有意義的東西嗎?

+0

您是否嘗試使用'StructuredFormatDisplay'屬性註釋類型提供程序? – bytebuster

回答

2

我不認爲有一種方法可以攔截printfn "%A"對於由類型提供程序(不能修改)生成的現有類型的行爲。如果您可以修改類型提供程序,那麼可以將其更改爲爲生成的類型生成StructuredFormatDisplay屬性,但這不可能用於SqlDataConnection

如果您在F#Interactive中使用它,那麼您可以使用fsi.AddPrintTransformer來定義當計算結果爲某個值時如何打印各個值。例如:

// Using Northwind database as a sample 
type DB = SqlDataConnection<"Data Source=.\\SQLExpress;Initial Catalog=Northwind;..."> 
let db = DB.GetDataContext() 

// A simple formatter that creates a list with property names and values 
let formatAny (o:obj) = 
    [ for p in o.GetType().GetProperties() -> 
     p.Name, p.GetValue(o) ] 

// Print all Northwind products using the formatter 
fsi.AddPrintTransformer(fun (p:DB.ServiceTypes.Products) -> 
    formatAny p |> box) 

// Take the first product - will be printed using custom formatter 
query { for p in db.Products do head } 

指定PrintTransformer當你的價值在F#互動的結果纔會被使用。當您爲返回多個對象的查詢編寫query { .. } |> List.ofSeq時,它也會起作用。但對於printfn "%A",您必須明確地調用轉換函數(如formatAny)...