现在的位置: 首页 > 综合 > 正文

.Net C# 关于反射的学习(一):获取类型、应用程序集信息

2013年03月03日 ⁄ 综合 ⁄ 共 2440字 ⁄ 字号 评论关闭

 反射机制的第一个练习,通过反射机制,获取类型,获取类型的成员信息。

using System;
using System.Reflection;

namespace TestReflection
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            
//ChineseName cn = new ChineseName();//获取类型方法一
            
//Type tcn = cn.GetType(); 
            Type tcn = Type.GetType("TestReflection.ChineseName");//获取类型方法二
            
//Assembly assemble=this.GetType().Assembly;//获取类型的方法三: 通过Assamble实例:
            
//Type tcn = assamble.GetType("TestReflection.ChineseName");
            
            
//Console.WriteLine("类型完全名称: " + tcn.FullName);  //获取类型完全名称
            
//Console.WriteLine("类型第一个成员名称: " + tcn.GetMembers()[0].Name);  //获取类型第一个成员名称
            
//Console.WriteLine("类型第一个方法名称: " + tcn.GetMethods()[0].Name);  //获取类型第一个方法名称
            
           Assembly curAssembly 
= tcn.Assembly;
            
//循环输出assembly中的类型及其成员信息
           Type[] types = curAssembly.GetTypes();
            
foreach (Type type in types)
           
{
               Console.WriteLine(
"【类名】"+type.FullName);
                
//获取类型的结构信息
                ConstructorInfo[] myconstructors = type.GetConstructors();
                Show(myconstructors);
               
//获取类型的字段信息
                FieldInfo[] myfields = type.GetFields();
               Show(myfields);
                
//获取方法信息
                MethodInfo[] myMethodInfo = type.GetMethods();
                Show(myMethodInfo);
               
//获取属性信息
                PropertyInfo[] myproperties = type.GetProperties();
               Show(myproperties);
                
//获取事件信息,这个项目没有事件,所以注释掉了,
               
//通过这种办法,还可以获得更多的type相关信息.
                
//EventInfo[] Myevents = type.GetEvents();
                
//Show(Myevents);
           }


           Assembly[] myAssemblies 
= AppDomain.CurrentDomain.GetAssemblies(); //获取所有的应用程序集
           foreach (Assembly myAssembly in myAssemblies)
           
{
               Console.WriteLine(
"Assembly的名字:" + myAssembly.ToString());
           }

           Console.WriteLine(
"最初指定的程序集TestReflection的位置:" + Assembly.Load("TestReflection").CodeBase);
           Console.ReadLine();
        }


        
static void Show(object[] obj)
        
{
            
foreach (object tmp in obj)
            
{
                Console.WriteLine(tmp);
            }

        }

    }


    
interface IName
    
{
        
void ShowName();
    }

    
class ChineseName:IName
    
{
        
public void ShowName()
        
{
            Console.WriteLine(
"我叫杰克。");
        }

    }

}

百思特网络 www.bestwl.com

抱歉!评论已关闭.