2012-10-30 29 views
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 Output

當我在.NET 4.0上運行此程序,所有屬性都可以正確找到。下面是輸出:

.NET 4.0 Output

那是存在於.NET 3.5和固定在.NET 4.0中這只是一個簡單的錯誤?還是有一些其他的微妙之處,我錯過了,這將允許我訪問內部抽象屬性的屬性?

注意:對於僅在具體類中被覆蓋的虛擬屬性時,這似乎也是如此。

回答

1

我重現了您所看到的並查看了Microsoft Connect。沒有報告的問題(由公衆)列出了GetCustomAttribute內部故障問題。 但這並不意味着它沒有被發現並在內部修復

您可以將其作爲連接問題發佈(link),並查看是否存在與.Net 3.5相關的熱修復。