關於反射一些總結

1.創建實體

//加載程序集ConsoleApplication9,直接加載。

    Assembly ass = Assembly.Load("ConsoleApplication9");

//加載程序集,通過文件
            Assembly ass1 = Assembly.LoadFile(AppDomain.CurrentDomain.BaseDirectory+"ConsoleApplication9.exe");

//創建ConsoleApplication9中的Person
            //var a2s = ass1.CreateInstance("ConsoleApplication9.Person");
            var a2s = ass1.CreateInstance("ConsoleApplication9.Person");

person如下類:

View Code
  public  class Person {

[DisplayAttribute(Description="姓名")]
public string Name { set; get; }
[DisplayAttribute(Description = "年齡")]
public int Age { set; get; }
[DisplayAttribute(Description = "返回方法")]
public string GetVal() {
return "223";
}
public int CurrentAge;
}

2.通過反射,讀取信息

   Type t = typeof(Person);

//得到類型的所有信息(包括方法,屬性,字段)
            var fils = t.GetMembers();

//得到所有的屬性
            var p=t.GetProperties();

//得到所有的字段
            var fs= t.GetFields();

//得到所有的方法
            var ms = t.GetMethods();

讀取所有的信息中的Attribute屬性

代碼如下:

View Code
       foreach (MemberInfo m in fils)
{
foreach (Attribute a in m.GetCustomAttributes(true))
{
DisplayAttribute d = a as DisplayAttribute;
if (d != null)
{
Console.Write(d.Description);
Console.WriteLine("{0}類中的{1}方法{2}屬性{3}", t.Name, m.Name,d.GetType().Name, d.Description);
}
else {
Console.WriteLine("{0}類中的{1}方法", t.Name, m.Name);
}

}
}

3.根據type 創建實體,調用方法等

// 創建Person類

           Type t = typeof(Person);

          Object obj = t.InvokeMember(null,
            BindingFlags.DeclaredOnly |
            BindingFlags.Public | BindingFlags.NonPublic |
            BindingFlags.Instance | BindingFlags.CreateInstance, null, null, null);
//調用person類中的GetVal方法
           var t2 = t.InvokeMember("GetVal",
              BindingFlags.DeclaredOnly |
              BindingFlags.Public | BindingFlags.NonPublic |
              BindingFlags.Instance | BindingFlags.InvokeMethod, null, obj, null);
              var atts= Attribute.GetCustomAttributes(typeof(Person).Assembly);


posted @ 2012-03-07 20:26  無限遐想  阅读(1079)  评论(0编辑  收藏  举报