在这个代码片断中Joseph 测试了一个使用 C# 反射来自动实现属性时发生了一个意想不到行为的方案之后提供了该方案的分步说明他提供了示例项目最终输出的截图相关的 C# 完整代码Visual Studio 的项目下载
Code
Listing : Employeecs
using System;
namespace CompilerGeneratedProps
{
public class Employee : Person
{
//Fields
protected string Title;
}
}
Listing : Personcs
using System;
namespace CompilerGeneratedProps
{
public class Person
{
//Fields
protected string _LastName; //Declared protected for extensibility
//Properties
public string FirstName { get; set; } //Autoimplemented property
public string LastName
{
get
{
return this_LastName;
}
set
{
this_LastName = value;
}
}
}
}
Listing : Programcs
using System;
using SystemReflection;
namespace CompilerGeneratedProps
{
public class Program
{
static void Main(string[] args)
{
ConsoleWriteLine(Fields seen in an instance of Person);
ConsoleWriteLine();
Person objPerson = new Person();
foreach (FieldInfo fi in
objPersonGetType()GetFields(BindingFlagsInstance |
BindingFlagsNonPublic | BindingFlagsPublic))
{
ConsoleWriteLine(fiName);
}
ConsoleWriteLine(\n\n\n\nFields seen in an instance of Employee);
ConsoleWriteLine();
Employee objEmployee = new Employee();
foreach (FieldInfo fi in
objEmployeeGetType()GetFields(BindingFlagsInstance |
BindingFlagsNonPublic | BindingFlagsPublic))
{
ConsoleWriteLine(fiName);
}
ConsoleRead();
}
}
}
结果输出
项目下载[Download Source]
结论
如果在一个父类中使用自动实现属性使用反射来收集一个派生类的字段将不会获得对应于上述所说的属性字段经典方法在这种情况下编码属性会更好