Created
July 16, 2012 06:11
-
-
Save juven/3121028 to your computer and use it in GitHub Desktop.
how to use customized c# attributes
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
using System; | |
using System.Collections.Generic; | |
using Microsoft.VisualStudio.TestTools.UnitTesting; | |
namespace RTP_Composite | |
{ | |
[TestClass] | |
public class AttributeSpike | |
{ | |
[TestMethod] | |
public void TryAttributes() | |
{ | |
Sut sut = new Sut(); | |
var keys = new List<string> {"toc", "print"}; | |
foreach ( var method in typeof (Sut).GetMethods()) | |
{ | |
var attr = (LoadFromXmlAttribute)Attribute.GetCustomAttribute(method, typeof(LoadFromXmlAttribute)); | |
if ( attr!=null && keys.Contains(attr.Key)) | |
{ | |
method.Invoke(sut, null); | |
} | |
} | |
} | |
} | |
class Sut | |
{ | |
[LoadFromXml("toc")] | |
public void MethodA() | |
{ | |
Console.WriteLine("Method A called"); | |
} | |
[LoadFromXml("print")] | |
public void MethodB() | |
{ | |
Console.WriteLine("Method B called"); | |
} | |
[LoadFromXml("oops")] | |
public void MethodC() | |
{ | |
Console.WriteLine("Method C called"); | |
} | |
} | |
[AttributeUsage(AttributeTargets.Method)] | |
internal sealed class LoadFromXmlAttribute : Attribute | |
{ | |
private readonly string m_key; | |
public LoadFromXmlAttribute(string key) | |
{ | |
m_key = key; | |
} | |
public string Key | |
{ | |
get { return m_key; } | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment