속성이 내부로 표시되면 추상 클래스에 정의 된 속성의 특성에 액세스하는 데 문제가 있습니다. 여기에 몇 가지 예제 코드입니다 : 내가 .NET 3.5에서이 프로그램을 실행하면내부 추상 속성 - 사용자 지정 특성
[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();
}
}
에서, LastName
재산에 속성이 발견되지는 출력은 다음과 같다 :
때 I을 .NET 4.0에서이 프로그램을 실행하면 모든 속성이 올바르게 발견됩니다.
가 .NET 3.5의 존재 및 .NET 4.0에서 수정되었습니다이 단순히 버그가 : 여기 출력은? 아니면 내부 추상 속성의 속성에 액세스 할 수 있도록 내가 누락 된 다른 미묘한 점이 있습니까?
참고 : 이는 가상 클래스가 콘크리트 클래스에서 재정의 된 경우에만 해당됩니다.