当前位置导航:炫浪网>>网络学院>>编程开发>>Visual C#教程

C# 自动实现属性的意想不到行为

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

共2页 首页 上一页 1 2 下一页 尾页 跳转到
相关内容
赞助商链接