因此,为了在运行时查看当前对象的状态,我非常喜欢Visual Studio立即窗口给出的内容.只是做一个简单的
? objectname
Run Code Online (Sandbox Code Playgroud)
将给我一个格式良好的"转储"对象.
有没有一种简单的方法在代码中执行此操作,因此我可以在记录时执行类似的操作?
想象一下有很多公共财产的班级.出于某种原因,不可能将此类重构为较小的子类.
我想添加一个ToString覆盖,返回以下内容:
Property 1: Value of property 1\n Property 2: Value of property 2\n ...
有没有办法做到这一点?
为了帮助调试我正在处理的一些代码,我开始编写一个方法来递归地打印出对象属性的名称和值.但是,大多数对象都包含嵌套类型,我也想打印它们的名称和值,但仅限于我定义的类型.
这是我到目前为止的概述:
public void PrintProperties(object obj)
{
if (obj == null)
return;
Propertyinfo[] properties = obj.GetType().GetProperties();
foreach (PropertyInfo property in properties)
{
if ([property is a type I have defined])
{
PrintProperties([instance of property's type]);
}
else
{
Console.WriteLine("{0}: {1}", property.Name, property.GetValue(obj, null));
}
}
Run Code Online (Sandbox Code Playgroud)
支架之间的部件是我不确定的地方.
任何帮助将不胜感激.
所以我正在尝试编写一个C#函数print_r(),它以与PHP print_r()函数相同的方式打印出有关传递值的信息.
我正在做的是接受一个对象作为函数的输入,并根据它的类型,我将输出值,或循环数组并打印出数组内的值.我打印出基本值没有问题,但当我尝试循环访问该对象时,如果我检测到它是一个数组,我从C#中得到一个错误,说"错误1 foreach语句不能对'object'类型的变量进行操作,因为'对象' '不包含'GetEnumerator'的公共定义".
现在我假设这只是因为对象没有实现IEnumerable <>,但有没有办法可以处理这个输入作为类型对象?
这是我当前的函数代码(IEnumerable <>部分在内容方面是空白的,但这是给我一个错误的代码.
谢谢.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;
using System.Reflection;
namespace ConsoleApplication1
{
class Program
{
static void print_r(object val)
{
if (val.GetType() == typeof(string))
{
Console.Write(val);
return;
}
else if (val.GetType().GetInterface(typeof(IEnumerable).FullName) != null)
{
foreach (object i in val)
{
// Process val as array
}
}
else
{
Console.Write(val);
return;
}
}
static void Main(string[] args)
{
int[] x = { 1, 4, 5, 6, 7, …Run Code Online (Sandbox Code Playgroud)