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