在這個代碼片斷中,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();
}
}
}
結果輸出:
結論
如果在一個父類中使用自動實現屬性,使用反射來收集一個派生類的字段將不會獲得對應於上述所說的屬性字段。經典方法在這種情況下編碼屬性會更好。