2014-10-01 177 views
2

無法編譯此F#代碼,因爲它不正確地從C#中轉換。無法編譯此F#代碼

似乎存在與lambda表達式

namespace OpenXML 

open DocumentFormat.OpenXml 
open DocumentFormat.OpenXml.Packaging 
open DocumentFormat.OpenXml.Wordprocessing 
// Add the DocumentFormat.OpenXml assembly 
// Add the WindowsBase assembly 

module public Word = 

    let query_plain_text_content_control (document_path_and_file_name :string) (content_control_tag :string) = 
     use theDoc = WordprocessingDocument.Open(document_path_and_file_name, true) 
     let mainPart = theDoc.MainDocumentPart 
     let block = mainPart.Document.Body.Descendants<SdtElement>().Where(r :> r.SdtProperties.GetFirstChild<Tag>().Val = content_control_tag).Single() 
     let t = block.Descendants<Text>().FirstOrDefault() 
     t.Text 

    let update_plain_text_content_control (document_path_and_file_name :string) (content_control_tag :string) (new_text :string) = async { 
     use theDoc = WordprocessingDocument.Open(document_path_and_file_name, true) 
     let mainPart = theDoc.MainDocumentPart 
     let block = mainPart.Document.Body.Descendants<SdtElement>().Where(r :> r.SdtProperties.GetFirstChild<Tag>().Val = content_control_tag).Single() 
     let t = block.Descendants<Text>().FirstOrDefault() 
     t.Text = new_text 
     mainPart.Document.Save() |> ignore 
     } 
+1

您應該確保包含確切的錯誤消息及其發生的行。 – crashmstr 2014-10-01 16:05:02

+0

歡迎!請包括您得到的確切錯誤。 – 2014-10-01 16:05:13

+0

錯誤意外的符號表達式中的'(',第14行, 錯誤綁定中的意外符號')'。在此點或其他標記之前或之前預期的不完整結構化構造。 \t第14行, 錯誤意外的符號'('在表達式中,第21行,錯誤意外的符號')'在綁定中。在此點或其他標記之前或之前預期的不完整結構化構造。 \t第21行 – 2014-10-01 16:16:35

回答

2

一個問題「:>」在F#是鑄造操作者,其轉換類型鍵入處於較高分層。這不是一個lambda表達式。所以可能這個調用

Where(r :> r.SdtProperties.GetFirstChild<Tag>().Val = content_control_tag) 

應該使用F#lambda語法改寫爲

Where(fun r -> r.SdtProperties.GetFirstChild<Tag>().Val = content_control_tag) 

。 也肯定這需要像「R」參數類型註釋:

Where(fun (r: put_here_type_of_r) -> ...) 

LINQ的擴展方法通常看起來醜陋在F#所以最好使用功能從Collection.Seq模塊:http://msdn.microsoft.com/en-us/library/ee353635.aspx(SEQ是別名IEnumerable <> in F#)

另外F#中的t.Text = new_text不是賦值而是相等性測試。如果您想爲可變變量指定一個新值,您應該使用賦值運算符:t.Text <- new_text

+0

我不同意使用'Seq'函數通常會更好 - 如果代碼使用表達式樹來編譯查詢,那麼'Seq'函數會做出非常不同的事情。 – kvb 2014-10-01 20:36:31

+0

@kvb是的,但在簡單過濾或映射的情況下F#函數具有很強的可讀性 – Petr 2014-10-01 20:43:10