I wanna have all properties of an object which have primitive type, and if the object has a relation to another class , I wanna have the primitive properties of this another
I am bored at work waiting for a build, have fun with your homework ;)
namespace Scratchpad
{
public static class TypeExtractor
{
public static IEnumerable ExtractTypes(this Type owner, HashSet visited = null)
{
if (visited == null)
visited = new HashSet();
if (visited.Contains(owner))
return new Type[0];
visited.Add(owner);
switch (Type.GetTypeCode(owner))
{
case TypeCode.Object:
break;
case TypeCode.Empty:
return new Type[0];
default:
return new[] {owner};
}
return
owner.GetMembers(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance |
BindingFlags.Static |
BindingFlags.FlattenHierarchy)
.SelectMany(x => x.ExtractTypes(visited)).Union(new[] {owner}).Distinct();
}
public static IEnumerable ExtractTypes(this MemberInfo member, HashSet visited)
{
switch (member.MemberType)
{
case MemberTypes.Property:
return ((PropertyInfo) member).PropertyType.ExtractTypes(visited);
break;
case MemberTypes.Field:
return ((FieldInfo) member).FieldType.ExtractTypes(visited);
default:
return new Type[0];
}
}
}
public class A
{
public string Name { get; set; }
public B B { get; set; }
}
public class B
{
public string Category { get; set; }
public A A { get; set; }
}
internal class Program
{
private static void Main(string[] args)
{
var q = typeof (A).ExtractTypes();
foreach (var type in q)
{
Console.Out.WriteLine(type.Name);
}
}
}
}