An attribute is an object attached to the Type of an object - you can change it's values at runtime.
The effect would be similar to declaring a static value in the class itself. Probably why this isn't a something you'll see all that often. - hmm, that wasn't exactly correct, sorry ...
Seems something like this is required:
using System;
using System.Collections.Generic;
using System.Reflection;
namespace Harlinn.CP.AttributeTest
{
[AttributeUsage(AttributeTargets.All)]
public class MyAttribute : Attribute
{
private static Dictionary<string, string> values = new Dictionary<string, string>();
private string key;
public MyAttribute(string key,string text)
{
this.key = key;
if (values.ContainsKey(key) == false)
{
values[key] = text;
}
}
public string Text
{
get { return values.ContainsKey(key)? values[key]:string.Empty; }
set { if (Text == value) { return; } values[key] = value; }
}
}
class Program
{
static void Main(string[] args)
{
MyMethod("Test1");
MyMethod("Test2");
}
[My("MyMethod", "Initial")]
private static void MyMethod(string text)
{
MethodBase method = MethodBase.GetCurrentMethod();
object[] attributes = method.GetCustomAttributes(typeof(MyAttribute),false);
MyAttribute myAttribute = attributes[0] as MyAttribute;
if (myAttribute != null)
{
Console.Out.WriteLine(myAttribute.Text);
myAttribute.Text = text;
Console.Out.WriteLine(myAttribute.Text);
}
}
}
}
To get rid of the key in the destructor, you'll probably to do an initial analysis of where it's applied - possibly using Type.Fullname + member as key, looking it up seems to require a similar effort, so maybe passing the key is a reasonable solution.
outputs:
Initial
Test1
Test1
Test2
Best regards
Espen Harlinn