2017-05-24 84 views
0

我寫一個使用的Microsoft Dynamics CRM API來用用CRM給出的EntityCollection獲取信息的表格的程序。我的問題是,該實體是由KeyValuePair<string, object>組成,這導致頭痛。運行時kvps中的一些對象類型爲OptionSetValue,我需要一種實際訪問值的方式,因爲OptionSetValue需要額外的存取器。轉換對象類型Microsoft.Xrm.Sdk.OptionSetValue型

下面是一些例子代碼來證明我的問題(「E」是實體):

foreach (KeyValuePair<string, object> thePair in e.Attributes.ToList()) 
{ 
    int theResult = thePair.Value; 
} 

在上面的例子中,程序將編譯,但在運行時將拋出厚望,因爲它會嘗試從轉換OptionSetValueint32

這是我想以某種方式完成的:

foreach (KeyValuePair<string, object> thePair in e.Attributes.ToList()) 
{ 
    int theResult = thePair.Value.Value; 
} 

在這種情況下的.Value訪問將返回我需要的價值,但因爲C#編譯器不知道thePairOptionSetValue型的,直到運行時,它將不會編譯,因爲對象類型沒有.Value成員。

任何想法或需要澄清我的問題?

回答

0

它似乎打字出這一切給了我一些清晰度我之後不到5分鐘這篇文章修復了這個問題。你可以簡單地使用強制轉換(OptionSetValue)

foreach (KeyValuePair<string, object> thePair in e.Attributes.ToList()) 
{ 
    int theResult = (OptionSetValue)thePair.Value.Value; 
}