Please consider the following code. I am surprised to learn that output is double "Base" rather than "Base" followed by "Derived".
Is there something that I am doing wrong? Can this be written differently to get the custom attribute based on an expression. It appears as if expressions will always use the base class.
The commented line proves that the custom attribute is accessible via reflection.
public static class Program
{
private static void Main(string[] args)
{
Write((Derived data) => data.Code);
Write((Base data) => data.Code);
// Console.WriteLine(typeof(Derived).GetProperty(nameof(Derived.Code)).GetCustomAttributes<XmlElementAttribute>().First().ElementName);
}
private static void Write<T1,T2>(Expression<Func<T1,T2>> expression)
{
Console.WriteLine(((MemberExpression) expression.Body).Member.GetCustomAttribute<XmlElementAttribute>().ElementName);
}
}
public abstract class Base
{
[XmlElement("Base")]
public abstract string Code { get; set; }
}
public class Derived : Base
{
[XmlElement("Derived")]
public override string Code { get; set; }
}
GetCustomAttribute(false)does not change anything.Memberin both cases seems to referenceBase.