在這個代碼片斷中,Joseph 測試了一個使用 C# 反射來自動實現屬性時,發生了一個意想不到行為的方案。之後提供了該方案的分步說明,他提供了示例項目最終輸出的截圖、相關的 C# 完整代碼、Visual Studio 2008的項目下載。
Code
Listing 1: Employee.cs
using system;
namespace CompilerGeneratedProps
{
public class Employee : Person
{
//Fields
protected string Title;
}
}
Listing 2: Person.cs
using system;
namespace CompilerGeneratedProps
{
public class Person
{
//Fields
protected string _LastName; //Declared protected for extensibility.
//Properties
public string FirstName { get; set; } //Auto-implemented property.
public string LastName
{
get
{
return this._LastName;
}
set
{
this._LastName = value;
}
}
}
}
Listing 3: Program.cs
using system;
using system.Reflection;
namespace CompilerGeneratedProps
{
public class Program
{
static void Main(string[] args)
{
Console.WriteLine("Fields seen in an instance of Person");
Console.WriteLine("-------------------------------------------------------");
Person objPerson = new Person();
foreach (FieldInfo fi in
objPerson.GetType().GetFields(BindingFlags.Instance |
BindingFlags.NonPublic | BindingFlags.Public))
{
Console.WriteLine(fi.Name);
}
Console.WriteLine("\n\n\n\nFields seen in an instance of Employee");
Console.WriteLine("-------------------------------------------------------");
Employee objEmployee = new Employee();
foreach (FieldInfo fi in
objEmployee.GetType().GetFields(BindingFlags.Instance |
BindingFlags.NonPublic | BindingFlags.Public))
{
Console.WriteLine(fi.Name);
}
Console.Read();
}
}
}
結果輸出:
結論
如果在一個父類中使用自動實現屬性,使用反射來收集一個派生類的字段將不會獲得對應於上述所說的屬性字段。經典方法在這種情況下編碼屬性會更好。