【翻译】代码片段:C# 自动实现属性的意想不到行为
摘要
在这个代码片断中,Joseph 测试了一个使用 C# 反射来自动实现属性时,发生了一个意想不到行为的方案。之后提供了该方案的分步说明,他提供了示例项目最终输出的截图、相关的 C# 完整代码、Visual Studio 2008的项目下载。
Listing 1: Employee.cs
using System;
namespace CompilerGeneratedProps
{
public class Employee : Person
{
//Fields
protected string Title;
}
}
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;
}
}
}
}
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();
}
}
}
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();
}
}
}
结果输出:
项目下载:[Download Source]
结论
如果在一个父类中使用自动实现属性,使用反射来收集一个派生类的字段将不会获得对应于上述所说的属性字段。经典方法在这种情况下编码属性会更好。