2009-06-18 36 views
0

我正在使用Reflection通過PropertyInfo.SetValue()設置屬性值;有問題的屬性是一個字符串,我從中獲取值的對象實際上是一個GUID。我想從一個GUID轉換爲過程中的字符串 - 是否有任何方式來定義某種隱式轉換將啓用此?目前,我得到一個錯誤:通過反射將GUID轉換爲字符串

"Object of type 'System.Guid' cannot be converted to type 'System.String'." 

我想我可以做一個類型檢查和手動轉換,如果有必要,但如果有做幕後的一種優雅的方式,那麼這將是最好!

非常感謝。


編輯: 我真的不能只需撥打一個GUID的的ToString()方法,我倒是很喜歡我的代碼看起來像這樣:

propertyInfoInstance.SetValue(classInstance, objectWithValue, null) 

哪裏objectWithValue是一個int/bool/string/GUID。這適用於除GUID之外的所有內容,因爲(我認爲!!)有可用的隱式轉換。我可以事先進行一次類型檢查,並將GUID轉換爲一個字符串,但我只是明白「必須有更好的方式......」的感覺。

回答

3

這是我的理解(有人請糾正我,如果這是錯誤的),你只能爲自己的對象定義隱式轉換運算符。

你需要手動處理傾銷GUID爲字符串W/guid.ToString();

+0

不幸的是,我認爲這是正確的。關鍵似乎是因爲你給出的原因,在這種情況下不可能定義隱式轉換,所以我將不得不手動處理這種情況 - 不重要的代碼,但亂! – 2009-06-19 08:55:24

3

我不相信字符串和GUID之間有隱式轉換。試試這個:

guid.ToString(); 

問題2:

if(propertyInfoInstance.PropertyType == typeof(string) && objectWithValue != null) 
{ 
    objectWithValue = objectWithValue.ToString(); 
} 
propertyInfoInstance.SetValue(classInstance, objectWithValue, null); 

我不認爲這是太亂了。

+0

+1這是正確的。字符串和guid之間沒有隱式轉換。 – 2009-06-18 15:19:03

0

你有沒有對GUID參考試過的ToString()?

0

你可以寫這樣的事情:

object myValue = /* source the value from wherever */; 
if (!(myValue is string)) myValue = myValue.ToString(); 

然後調用PropertyInfo.SetValue()與myvalue的。

相關問題