Skip to content

Instantly share code, notes, and snippets.

@jskripsky
Created August 12, 2011 09:58
Show Gist options
  • Save jskripsky/1141804 to your computer and use it in GitHub Desktop.
Save jskripsky/1141804 to your computer and use it in GitHub Desktop.
Get all fields (following inheritance chain) using Chain<T>(Func<T, T>) extension method.
using System;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
static class Helper {
public static IEnumerable<T> Chain<T>(this T first, Func<T, T> follow) where T : class {
for (T item = first; item != null; item = follow(item))
yield return item;
}
}
class Test {
static void Main() {
Type t = typeof(SomeDerived);
BindingFlags flags =
BindingFlags.Instance | BindingFlags.DeclaredOnly |
BindingFlags.Public | BindingFlags.NonPublic;
var fields = t.Chain(type => type.BaseType).SelectMany(type => type.GetFields(flags));
foreach(FieldInfo fi in fields)
Console.WriteLine(fi.Name);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment