2013-02-22 128 views
0

爲了測試的目的,我想看看HttpApplication對象的所有屬性及其相應的值(我正在測試HTTPModule的某些功能)。我的第一個想法是將其序列化爲XML,然後查看它或將其寫入文件。可能序列化一個不可序列化的對象?

問題是,HttpApplication不是一個可序列化的類,所以當我嘗試序列化時拋出異常。是否還有其他技術,或者甚至有可能獲得不可序列化對象的字符串表示形式?我只想看看所有與Intellisense相同的屬性及其值。

我見過一些提到Reflection的文章,但是我還沒有找到任何暗示它適用於我的場景的文章。

UPDATE:

得到一對夫婦的響應後,它看起來像我需要使用反射。下面是我使用的代碼:

Dim sProps As New StringBuilder 
For Each p As System.Reflection.PropertyInfo In oHttpApp.GetType().GetProperties() 
    If p.CanRead Then 
    sProps.AppendLine(p.Name & ": " & p.GetValue(oHttpApp, Nothing)) 
    End If 
Next 

在我AppendLine聲明,拋出一個異常的時候了:

System.InvalidCastException:運營商「&」字符串 「環境未定義:「並鍵入'HttpContext'。在 Microsoft.VisualBasic.CompilerServices.Operators.InvokeObjectUserDefinedOperator在 Microsoft.VisualBasic.CompilerServices.Operators.InvokeUserDefinedOperator(UserDefinedOperator 運算,對象[]參數)(UserDefinedOperator 運算,對象[]參數)在 Microsoft.VisualBasic.CompilerServices。 Operators.ConcatenateObject(對象 左,右對象)

@granadaCoder,您提到,我需要知道如何「深」走,我不知道是否這就是問題所在。在上面的錯誤中,Context是一個複雜的對象,所以我需要鑽取該對象並獲取其各個屬性,是否正確?你知道我怎麼能夠做到這一點 - 或者它會像在我的循環內的p上再次呼叫GetProperties一樣簡單嗎?

+0

我會做Dim o作爲Object = p.GetValue(oHttpApp,Nothing)。看看是什麼,然後嘗試寫出來。你可能需要嵌套某些類型的調用(也就是說,檢查「o」的類型,然後遞歸地調用你的例程.....如果調用它們導致excepiton,你可能不得不忽略其他幾個。阿卡,你的代碼可能會被非常定製。請記住,我「米不是一個反思的專家。 – granadaCoder 2013-02-22 16:38:59

回答

2

聽起來像是不錯的使用情況reflection--

How to iterate through each property of a custom vb.net object?

你可以遍歷所有對象的屬性,併爲它們創建自己的XML/JSON視圖。

Update--

這裏是我如何把任何物體的字典(這會爲你的使用情況工作)的C#代碼

public static Dictionary<string,string> ToDictionary<T>(this T me, string prefix=null) where T:class 
    { 
     Dictionary<string, string> res = new Dictionary<string, string>(); 

     if (me == null) return res; 


     var bindingFlags = BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty | BindingFlags.GetField; 
     var properties = me.GetType().GetProperties(bindingFlags) 
      .Where(i => i.CanRead 
      ); 

     foreach (var i in properties) 
     { 
      var val = i.GetValue(me, null); 
      var str = ""; 
      if (val != null) 
       str = val.ToString(); 
      res[string.Format("{0}{1}", prefix, i.Name)] = str; 
     } 
     return res; 
    } 
+0

現在我得到一個錯誤,請參閱我的更新以獲得更多信息。 – lhan 2013-02-22 16:13:33

+0

你需要確保該屬性是一個字符串 - 這意味着,當你叫'p.GetValue'這是一個HttpContext的 – Micah 2013-02-22 16:35:34

+0

嘗試'p.GetValue(oHttpApp,爲Nothing)的ToString()' – Micah 2013-02-22 16:38:44

1

某些對象並不意味着可序列化。以一個IDataReader爲例。

你必須去反思。並「取消」可讀的屬性。

這裏有一些入門的代碼。

private void ReadSomeProperties(SomeNonSerializableObject myObject) 
    { 

    foreach(PropertyInfo pi in myObject.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.GetProperty)) 
    { 
    //pi.Name 
    //pi.GetValue(myObject, null) 
    //don't forget , some properties may only have "setters", look at PropertyInfo.CanRead 
    } 

    } 

當然,當屬性是一個複雜的對象(不是標),那麼你必須搞清楚你如何「深」想去挖掘。

+0

謝謝!我更新了我的帖子,如果你能看到我做錯了什麼,請告訴我。 – lhan 2013-02-22 16:13:54

相關問題