C#变量描述功能

时间:2009-03-30 21:33:38

标签: c# .net

C#/ .net中是否有内置函数可以获取变量并描述/输出它的内容?在PHP中有print_r()var_dump()函数来实现这一点(我意识到C#和PHP之间的固有差异,仅提供输出示例)

由于这是一个日志记录脚本,它需要尽可能轻量级且不引人注目 - 我正在考虑编写一个函数来执行此操作,但是如果可用则更喜欢使用内置函数。

变量的示例是自定义对象的数组/列表,转出传递给事件处理程序的eventargs等。我想尽可能地采用它,同时避免反射费用。

由于

4 个答案:

答案 0 :(得分:1)

我不确定C#中的任何内置转储功能,但你可以简单地使用Reflection并使用 MethodInfo,PropertyInfo,FieldInfo 等迭代变量的类型。

编辑:是的,我知道它不是轻量级的。

答案 1 :(得分:1)

有关获取对象字符串表示形式的不同方法的摘要,请参阅我对此问题的回答:
String casts

由于您希望此功能非常通用且轻量级,因此最佳选择可能是Convert.ToString()

答案 2 :(得分:0)

我不懂PHP,但我想在你的班级中覆盖/实现ToString()是最接近的匹配。

E.g。对于类Person,您可以实现类似于此的ToString():

public override string ToString()
{
  return string.Format("{0} {1}", this.FirstName, this.LastName);
}

这将为Person的任何实例输出“firstname lastname”。

答案 3 :(得分:0)

没有内置方法,但这里是一个使用反射获取字段和属性的示例:

public static string DisplayObjectInfo(Object o)
{
   StringBuilder sb = new StringBuilder();

   // Include the type of the object
   System.Type type = o.GetType();
   sb.Append("Type: " + type.Name);

   // Include information for each Field
   sb.Append("\r\n\r\nFields:");
   System.Reflection.FieldInfo[] fi = type.GetFields();
   if (fi.Length > 0)
    {
      foreach (FieldInfo f in fi)
      {
         sb.Append("\r\n " + f.ToString() + " = " +
                   f.GetValue(o));
      }
   }
   else
      sb.Append("\r\n None");

   // Include information for each Property
   sb.Append("\r\n\r\nProperties:");
   System.Reflection.PropertyInfo[] pi = type.GetProperties();
   if (pi.Length > 0)
   {
      foreach (PropertyInfo p in pi)
      {
         sb.Append("\r\n " + p.ToString() + " = " +
                   p.GetValue(o, null));
      }
   }
   else
      sb.Append("\r\n None");

   return sb.ToString();
}

来源:http://www.developer.com/net/csharp/article.php/3713886

相关问题