Print_r () PHP Function in C #

So, I'm trying to write a C # print_r () function that prints information about a value passed in the same way as the PHP print_r () function.

What I am doing is taking an object as an input to a function, and depending on what type it will be, I will post a value or go through an array and print the values ​​inside the array. I have no problem printing basic values, but when I try to loop through an object, if I find that it is an array, I get an error with C #, in which: "Error 1 foreach statement cannot work with variables like" object because "object 'does not contain a public definition for" GetEnumerator ".

Now I assume that this happens only because the object does not implement IEnumerable <>, but is there a way I can treat this take in input as an object of type?

This is my current code for the function (the IEnumerable <> part is empty in content, but this is the code that gives me an error.

Thanks.

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(); } } } 
+4
source share
3 answers

val is declared as an object. After checking if it is IEnumerable (which you can do simply with is , as shown, but this also works with your source code), you must explicitly specify it

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

There is LINQPad that has a Dump () extension method, but you can only use it in LINQPad
We can write our own extension method to upload any object in html and view it in a browser.
You need to access LINQPad.exe

 public static class Extension { public static void Dump<T>(this T o) { string localUrl = Path.GetTempFileName() + ".html"; using (var writer = LINQPad.Util.CreateXhtmlWriter(true)) { writer.Write(o); File.WriteAllText(localUrl, writer.ToString()); } Process.Start(localUrl); } } 
0
source

You would need to use reflection for this, I think I need a similar function and output my objects to tables using reflection.

I have no code, but I found the basis of my solution here !

0
source

Source: https://habr.com/ru/post/1399965/


All Articles