当属性标记为内部时,我在访问抽象类中定义的属性的属性时遇到问题。这是一些示例代码:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)]
public class CustomAttribute : Attribute
{
}
public abstract class BaseModel
{
[CustomAttribute]
protected DateTimeOffset GenerationTime { get { return DateTimeOffset.Now; } }
[CustomAttribute]
public abstract string FirstName { get; } // Attribute found in .NET 3.5
[CustomAttribute]
internal abstract string LastName { get; } // Attribute not found in .NET 3.5
}
public class ConcreteModel : BaseModel
{
public override string FirstName { get { return "Edsger"; } }
internal override string LastName { get { return "Dijkstra"; } }
[CustomAttribute]
internal string MiddleName { get { return "Wybe"; } }
}
class Program
{
static void Main(string[] args)
{
ConcreteModel model = new ConcreteModel();
var props = model.GetType().GetProperties(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance).ToList();
List<PropertyInfo> propsFound = new List<PropertyInfo>(), propsNotFound = new List<PropertyInfo>();
for (int i = props.Count - 1; i >= 0; i--)
{
var att = Attribute.GetCustomAttribute(props[i], typeof(CustomAttribute), true) as CustomAttribute;
if (att != null)
propsFound.Add(props[i]);
else
propsNotFound.Add(props[i]);
}
Console.WriteLine("Found:");
foreach (var prop in propsFound)
{
Console.WriteLine(prop.Name + ": " + prop.GetValue(model, null));
}
Console.WriteLine(Environment.NewLine + "Not Found:");
foreach (var prop in propsNotFound)
{
Console.WriteLine(prop.Name + ": " + prop.GetValue(model, null));
}
Console.ReadKey();
}
}
当我在 .NET 3.5 上运行此程序时,LastName
找不到该属性的属性,输出如下:
当我在 .NET 4.0 上运行该程序时,所有属性都正确找到。这是输出:
这仅仅是 .NET 3.5 中存在并在 .NET 4.0 中修复的错误吗?还是我缺少其他一些微妙之处,可以让我访问内部抽象属性的属性?
注意:只有在具体类中重写虚拟属性时,这似乎也是正确的。