gpt4 book ai didi

c# - C# 中的 print_r() PHP 函数

转载 作者:太空狗 更新时间:2023-10-30 01:08:23 24 4
gpt4 key购买 nike

所以我正在尝试编写一个 C# 函数 print_r() 来打印出有关传递的值的信息,其工作方式与 PHP print_r() 函数的工作方式大致相同。

我正在做的是将一个对象作为函数的输入,并根据它的类型输出值,或者循环遍历数组并打印出数组中的值。我打印出基本值没有问题,但是当我尝试循环对象时,如果我检测到它是一个数组,我从 C# 中得到一个错误,说“错误 1 ​​foreach 语句无法对类型为‘object’的变量进行操作,因为‘object’ ' 不包含 'GetEnumerator' 的公共(public)定义。

现在我假设这只是因为对象没有实现 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, 8 };
print_r(x);
Console.Read();
}
}
}

最佳答案

val 声明为对象。在检查它是否是 IEnumerable 之后(您可以简单地使用 is 来完成,如图所示,但这也适用于您的原始代码)您必须显式转换它

else if (val is IEnumerable)
{
var e = val as IEnumerable;
foreach (var i in e)
{
Console.WriteLine(i.ToString());
}
}

关于c# - C# 中的 print_r() PHP 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9581014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com