反射使用方法

来源:互联网 发布:国家食药监局数据查询 编辑:程序博客网 时间:2024/05/03 21:30

//反射的使用方法
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);