Created
May 23, 2012 04:20
-
-
Save frankhale/2773248 to your computer and use it in GitHub Desktop.
Simple C# Reflection Example
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.Linq; | |
using System.Reflection; | |
namespace ReflectionExample | |
{ | |
[AttributeUsage(AttributeTargets.Method)] | |
class Foo : Attribute | |
{ | |
public string Bar { get; private set; } | |
public Foo(string bar) | |
{ | |
Bar = bar; | |
} | |
} | |
class A | |
{ | |
[Foo("Hello,World")] | |
public void Bar() | |
{ | |
} | |
} | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
A a = new A(); | |
MethodInfo m = a.GetType().GetMethods().FirstOrDefault(x => x.Name == "Bar"); | |
if (m != null) | |
{ | |
Foo f = (Foo)m.GetCustomAttributes(false).FirstOrDefault(x => x.GetType() == typeof(Foo)); | |
if (f != null) | |
{ | |
Console.WriteLine(f.Bar); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment