所以我正在尝试编写一个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) c# ×1