C# 自动实现属性

2008-08-05 13:56:48.0     推荐:0    收藏:0    评论:0     来源:中国IT实验室

在这个代码片断中,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();
}
}
}

[第1页]   [第2页]   [下一页]
您可以针对本文进行:[评论]  [收藏]  [推荐]  
  • 共有0条评论  点击查看更多评论
  • 网友评论仅供网友表达个人看法,并不表明e800同意其观点或证实其描述
我想发表评论:
用户名密码
  • 匿名发表
    验证码: