Created
May 30, 2013 14:20
-
-
Save benerdin/5678202 to your computer and use it in GitHub Desktop.
Code snippet for reflecting on a class and appending properties to a StringBuilder. For System types, this will ignore appending properties (e.g. the Length property won't be appended for System.String).
This file contains hidden or 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
| private string GetModelDescription() | |
| { | |
| var sb = new StringBuilder(); | |
| var type = typeof(YourType); | |
| sb.AppendFormat("{0} ({1})\n", type.Name, type.UnderlyingSystemType.ToString()); | |
| AppendPropertiesDescription(type, sb, " "); | |
| return sb.ToString(); | |
| } | |
| private void AppendPropertiesDescription(Type type, StringBuilder sb, string prefix) | |
| { | |
| type.GetProperties() | |
| .ForEach(prop => { | |
| var underlyingType = prop.PropertyType.UnderlyingSystemType; | |
| // Types we don't need to append | |
| if (!underlyingType.IsGenericType && prop.ReflectedType.Namespace.StartsWith("System")) | |
| return; | |
| // Append type | |
| sb.AppendFormat("{0}{1} ({2})\n", prefix, prop.Name, underlyingType.ToString()); | |
| if (underlyingType.IsGenericType) | |
| { | |
| // Type has a generic (e.g. List<object>). | |
| underlyingType.GenericTypeArguments | |
| .ForEach(genType => AppendPropertiesDescription(genType.UnderlyingSystemType, sb, prefix + " ")); | |
| } | |
| else | |
| { | |
| // Recursive call to append properties of property. | |
| AppendPropertiesDescription(prop.PropertyType.UnderlyingSystemType, sb, prefix + " "); | |
| } | |
| }); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment