Inside my application I encountered a strange situation with CustomAttributes and Reflection that I can't understand, I tried to reduce the problem. Suppose that I have following custom attributes:
class A : Attribute
{
public virtual string SayHi()
{
return "Hi From A";
}
}
class B : A
{
public override string SayHi()
{
return "Hi From B";
}
}
Following classes are decorated with custom attributes:
[A]
class X
{ }
[B]
class Y
{ }
In following method I map each type of classes decorated with "A" attribute to a function that returns the value returned by its custom attribute:
static Dictionary<Type, Func<string>> dic = new Dictionary<Type, Func<string>>();
static void func()
{
A attr;
foreach (var type in typeof(Program).Assembly.GetTypes())
{
var attrs = type.GetCustomAttributes(typeof(A)).ToList();
if(attrs.Any())
{
attr = attrs.First() as A;
dic.Add(type, () => attr.SayHi());
}
}
}
The function mapped to type of X might return "Hi From A" but strangely the following code prints "Hi From B" to the console!
func();
Console.WriteLine(dic[typeof(X)]());
Am I missing a language feature?