net技术中"反射"的使用方法

来源:互联网 发布:it项目招标 编辑:程序博客网 时间:2024/05/21 09:47

转(http://www.cnblogs.com/xiyang1011/archive/2009/08/02/reflection.html) 

本文主要介绍net技术中"反射"的使用方法,包括如何对属性赋值,获取变量,属性,方法,事件的列表,如何设置属性及调用方法等.希望对新人有所帮助咯.

 

//反射的使用方法

public class TestProperty

{

    private int i_seqnum = 0;

    private string s_authorid = string.Empty;

 

    public int SeqNum

    {

        get { return i_seqnum; }

        set { i_seqnum = value; }

    }

 

    public string AuthorID

    {

        get { return s_authorid; }

        set { s_authorid = value; }

    }

 

    public TestProperty()

    {

 

    }

 

    public TestProperty(string as_authorid)

    {

        this.AuthorID = as_authorid;

    }

 

    public void GetAuthorID()

    {

        if (s_authorid == "" || s_authorid == string.Empty)

        {

            System.Console.WriteLine("Null");

        }

        else

        {

            System.Console.WriteLine(s_authorid);

        }

 

    }

}

 

//调用方式

TestProperty test = new TestProperty();

Type t = test.GetType();

 

//列出类型的结构信息

System.Console.WriteLine("列出类型的结构信息");

ConstructorInfo[] test_constructor = t.GetConstructors();

foreach (ConstructorInfo item_constructor in test_constructor)

{

    System.Console.WriteLine(item_constructor.Name);

 

}

 

//列出TestProperty类中所有变量

System.Console.WriteLine("列出TestProperty类中所有变量");

FieldInfo[] test_field = t.GetFields();

foreach (FieldInfo item_field in test_field)

{

    System.Console.WriteLine(item_field.Name);

 

}

 

//列出TestProperty类中所有属性

System.Console.WriteLine("列出TestProperty类中所有属性");

PropertyInfo[] list_property = t.GetProperties();

foreach (PropertyInfo item_property in list_property)

{

    System.Console.WriteLine(item_property.Name);

}

 

//列出TestProperty类中所有方法

System.Console.WriteLine("列出TestProperty类中所有方法");

MethodInfo[] test_method = t.GetMethods();

foreach (MethodInfo item_method in test_method)

{

    System.Console.WriteLine(item_method.Name);

 

}

 

//列出TestProperty类中所有事件

System.Console.WriteLine("列出TestProperty类中所有事件");

EventInfo[] test_event = t.GetEvents();

foreach (EventInfo item_event in test_event)

{

    System.Console.WriteLine(item_event.Name);

 

}

 

//赋值

t.GetProperty("SeqNum").SetValue(test, 1, null);

t.GetProperty("AuthorID").SetValue(test, "ADB01", null);

//取值

int i_seqnum = Convert.ToInt32(t.GetProperty("SeqNum").GetValue(test, null));

string s_authorid = t.GetProperty("AuthorID").GetValue(test, null).ToString();

 

//使用反射调用方法

//test.GetAuthorID();

System.Console.WriteLine("使用反射调用方法");

string[] s = { "BC001" };

MethodInfo method_getauthorid = t.GetMethod("GetAuthorID");

//1种方法

object obj_name = Activator.CreateInstance(t, s);

method_getauthorid.Invoke(obj_name, null);

//2种方法

object obj = Activator.CreateInstance(t);

method_getauthorid.Invoke(obj, null);

原创粉丝点击