Skip to content

Instantly share code, notes, and snippets.

@juven
Created July 16, 2012 06:11
Show Gist options
  • Save juven/3121028 to your computer and use it in GitHub Desktop.
Save juven/3121028 to your computer and use it in GitHub Desktop.
how to use customized c# attributes
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