1

当属性标记为内部时,我在访问抽象类中定义的属性的属性时遇到问题。这是一些示例代码:

[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 3.5 输出

当我在 .NET 4.0 上运行该程序时,所有属性都正确找到。这是输出:

.NET 4.0 输出

这仅仅是 .NET 3.5 中存在并在 .NET 4.0 中修复的错误吗?还是我缺少其他一些微妙之处,可以让我访问内部抽象属性的属性?

注意:只有在具体类中重写虚拟属性时,这似乎也是正确的。

4

1 回答 1

1

我复制了您看到的内容并查看了 Microsoft Connect。没有报告的问题(公众)列出了 GetCustomAttribute 内部失败的问题。但这并不意味着它没有在内部被发现和修复

您可以将此作为连接问题(链接)发布,并查看是否有与 .Net 3.5 相关的热修复。

于 2012-10-30T17:07:08.840 回答