C#高级编程之“反射”

一,定义

   反射技术,能够让托管代码在运行时查看元数据以及代码的各方面信息。

 

二,常用方法

  1,获取对象方法(必须以Public修饰的方法,不包括构造函数);

  2,获取对象属性;

  3,获取对象的父类;

 

 

附示例代码:

using System;

using System.Collections.Generic;

using System.Text;

using System.Reflection;

 

/// <summary>

/// 基类

/// </summary>

public class Base

{

 

}

 

/// <summary>

/// 继承Base的子类

/// </summary>

public class Child : Base

{

    private int num = 1;

 

 

    public Child()

    {

 

    }

 

    public int Num

    {

        get

        {

            return num;

        }

        set

        {

            this.num = value;

        }

    }

 

    //在获取对象方法时,非Public修饰的方法是无法取得的,但包括构造函数

    private void testMethod1()

    {

 

    }

 

    public void testMethod2()

    {

       

    }

}

 

public class Program

{

 

    Child c = new Child();

 

    static void Main(string[] args)

    {

        Program p = new Program();

        System.Type cType = p.c.GetType();

 

        //获取对象方法

        MethodInfo[] methods = cType.GetMethods();

        Console.WriteLine("方法列表:");

        foreach (MethodInfo m in methods )

        {

            Console.WriteLine(m.Name );

        }

 

        //获取对象属性

        PropertyInfo[] propertys = cType.GetProperties();

        Console.WriteLine("属性列表:");

        foreach (PropertyInfo ps in propertys  )

        {

            Console.WriteLine(ps.Name );

        }

 

        //获取对象基类

        System.Type parent = cType.BaseType;

        Console.WriteLine("对象层次结构:");

        Console.Write(cType .FullName );

        while (parent !=null )

        {

            Console.Write("->" + parent .Name);

            parent = parent.BaseType;

        }

       

 

        Console.Read();

    }

}

 

运行结果:

方法列表:
get_Num
set_Num
testMethod2
GetType
ToString
Equals
GetHashCode
属性列表:
Num
对象层次结构:
Child->Base->Object 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值