Created
August 6, 2011 18:08
-
-
Save trbngr/1129580 to your computer and use it in GitHub Desktop.
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
public class Program | |
{ | |
private static void Main() | |
{ | |
var instance = new SomeClass | |
{ | |
SomePropertyWithAttribute = "I have an attribute", | |
SomeProperty = "I don't have an attribute" | |
}; | |
Inspect(instance); | |
Console.ReadKey(false); | |
} | |
private static void Inspect(SomeClass instance) | |
{ | |
var type = instance.GetType(); | |
foreach (var property in type.GetProperties()) | |
{ | |
var attribute = property.GetCustomAttributes(typeof(MyAttribute), false) | |
.Cast<MyAttribute>() | |
.FirstOrDefault(); | |
if(attribute != null) | |
{ | |
Console.Out.WriteLine("{0} = {1}", attribute.GetType().Name, attribute.Value); | |
} | |
Console.Out.WriteLine("{0} = {1}", property.Name, property.GetValue(instance, null)); | |
Console.Out.WriteLine(""); | |
} | |
} | |
} | |
public class SomeClass | |
{ | |
public string SomeProperty { get; set; } | |
[MyAttribute("MyValue")] | |
public string SomePropertyWithAttribute { get; set; } | |
} | |
[AttributeUsage(AttributeTargets.Property)] | |
public class MyAttribute : Attribute | |
{ | |
public MyAttribute(string value) | |
{ | |
Value = value; | |
} | |
public string Value { get; private set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment