2016-03-22 32 views
3

我想將一個對象轉換爲動態類型,但是轉換失敗並導致RunTimeBinder異常。我嘗試使用兩種方法,我遇到了Stackoverflow的答案。在C中將對象轉換爲動態類型#

代碼1:

object objSum; 
dynamic dynSum; 
objSum = dataTableColumnChart.Compute(String.Format("Count({0})", strColumnName), ""); 
dynSum = Convert.ChangeType(objSum, objSum.GetType());\ 
Debug.Writeline(dynSum); 

代碼2:

dynSum=objSum; 
Debug.Writeline(dynSum); 

引發的異常是:

A first chance exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in Unknown Module. 

請注意,在這兩種情況下,當調試語句拋出異常執行。

+0

你確定你的代碼是2嗎?我不認爲對動態類型的簡單賦值會導致異常。你能給出確切的錯誤信息嗎? – PMF

+0

@PMF嗨,我已經在我的問題中添加了詳細信息。 – JKay

+0

是使用Debug.Writeline(dynSum.ToString())引發的異常; – Eminem

回答

2

唯一的例外是:

Cannot dynamically invoke method 'Write' because it has a Conditional attribute 

當您檢查可能的Debug.WriteLine投入, 「動態」 是不是其中之一。 所以,你需要將其強制轉換,爲字符串,例如:

string strForWriteLine = dynSum.ToString() as string; 
    Debug.WriteLine(strForWriteLine); 

希望這有助於

*編輯: 一點點細節約dynSum.ToString()作爲字符串; 當你只使用ToString()時,你仍然會得到一個動態字符串。

var strForWriteLine = dynSum.ToString(); 

strForWriteLine的類型是動態{string}裏

+0

嗨,它現在正在工作。謝謝!所以轉換進行得很好,問題在於Debug,Writeline。感謝您的解釋。 – JKay

0

嘗試以下操作:

dynSum = objSum; 
+0

嗨,我已經試過這個,並在我的問題中提到。 – JKay

11

這裏是擴展方法來將對象轉換爲動態

public static dynamic ToDynamic(this object value) 
    { 
     IDictionary<string, object> expando = new ExpandoObject(); 

     foreach (PropertyDescriptor property in TypeDescriptor.GetProperties(value.GetType())) 
      expando.Add(property.Name, property.GetValue(value)); 

     return expando as ExpandoObject; 
    } 
0

你應該使用JsonConvert。所有的拳頭,序列化對象到字符串,然後反序列化字符串到動態。

string str = JsonConvert.SerializeObject(objectstring); 
dynamic obj = JsonConvert.DeserializeObject(str);