Created
October 21, 2014 14:34
-
-
Save DominicFinn/b6cc87f7e4dc699aa512 to your computer and use it in GitHub Desktop.
Dom and Ed messing about with some reflection and recursion
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Reflection; | |
using System.Text; | |
using System.Threading.Tasks; | |
namespace lol | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
var fooz = new[] | |
{ | |
new Foo() {Name = "Dom", Bar = new Bar() {Name = "Finn"}}, | |
new Foo() {Name = "Ed", Bar = new Bar() {Name = "Wilsoon"}} | |
}; | |
var typeOfFoo = typeof (Foo); | |
var header = GetProperties(typeOfFoo, new List<string>()); | |
foreach (var prop in header) | |
{ | |
Console.WriteLine(prop); | |
} | |
foreach (var foo in fooz) | |
{ | |
PrintProperties(foo); | |
} | |
Console.ReadKey(); | |
} | |
private static void PrintProperties(object foo) | |
{ | |
foreach (PropertyInfo propertyInfo in foo.GetType().GetProperties()) | |
{ | |
if (propertyInfo.PropertyType.IsClass && propertyInfo.PropertyType != typeof(string)) | |
{ | |
PrintProperties(propertyInfo.GetValue(foo)); | |
} | |
else | |
{ | |
Console.WriteLine(propertyInfo.GetValue(foo)); | |
} | |
} | |
} | |
static IList<string> GetProperties(Type something, IList<string> results) | |
{ | |
var properties = something.GetProperties(); | |
foreach (var propertyInfo in properties) | |
{ | |
if (propertyInfo.PropertyType.IsClass && propertyInfo.PropertyType != typeof(string)) | |
{ | |
GetProperties(propertyInfo.PropertyType, results); | |
} | |
else | |
{ | |
results.Add(propertyInfo.Name); | |
} | |
} | |
return results; | |
} | |
} | |
class Foo | |
{ | |
public string Name { get; set; } | |
public Bar Bar { get; set; } | |
} | |
class Bar | |
{ | |
public string Name { get; set; } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment