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 4.0上運行此程序,所有屬性都可以正確找到。下面是輸出:
那是存在於.NET 3.5和固定在.NET 4.0中這只是一個簡單的錯誤?還是有一些其他的微妙之處,我錯過了,這將允許我訪問內部抽象屬性的屬性?
注意:對於僅在具體類中被覆蓋的虛擬屬性時,這似乎也是如此。