開(kāi)發(fā)時(shí)有時(shí)會(huì )遇到一些需要實(shí)例化指定名稱(chēng)的類(lèi),這個(gè)時(shí)候要用到反射來(lái)實(shí)現了??梢詤⒄障旅娴目刂婆_示例:
需要實(shí)例化的類(lèi):
Class1.cs
using System;
using System.Collections.Generic;
using System.Text;
namespace shilihua
{
public class Class1
{
private string field;
public string demo1 = "123";
public string demo2 = "abc";
public string ReturnValue
{
set { field = value; }
get { return field; }
}
public void show()
{
Console.WriteLine("指定名稱(chēng)實(shí)例化的類(lèi)的方法");
}
}
}
Program.cs
using System;
using System.Collections.Generic;
using System.Text;
//引用的
using System.Reflection;
namespace shilihua
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("當前程序集:" + System.Reflection.Assembly.GetEntryAssembly().GetName().Name);
Class1 myclass = new Class1();
myclass.ReturnValue = "13";
Console.WriteLine(myclass.ReturnValue);
Console.WriteLine("demo1==>"+myclass.demo1);
Console.WriteLine("demo2==>" + myclass.demo2);
myclass.show();
Assembly asse = Assembly.Load(System.Reflection.Assembly.GetEntryAssembly().GetName().Name);//獲得程序集
Type type = asse.GetType(System.Reflection.Assembly.GetEntryAssembly().GetName().Name+".Class1");//class1是指定的類(lèi)名
//將得到的類(lèi)型傳給一個(gè)新建的構造器類(lèi)型變量
ConstructorInfo constructor = type.GetConstructor(new Type[0]);
//使用構造器對象來(lái)創(chuàng )建對象
object obj = constructor.Invoke(new Object[0]);
//輸出對象類(lèi)型
Console.WriteLine(obj);
//調用實(shí)例化實(shí)體的字段
FieldInfo[] f = type.GetFields();
Console.WriteLine("FieldInfo total ==>" + f.Length);
foreach (FieldInfo temp in f)
{
Console.WriteLine("field.Name==>" + temp.Name);
if (temp.Name.Equals("demo1"))
{
temp.SetValue(obj, "456");//設置字段的值
}
Console.WriteLine(temp.Name+"字段的值==>" + temp.GetValue(obj));
}
//調用實(shí)例化實(shí)體的屬性
PropertyInfo[] props = type.GetProperties();
Console.WriteLine("PropertyInfo total=" + props.Length);
foreach (PropertyInfo var in props)
{
if (var.Name.Equals("ReturnValue"))
{
Console.WriteLine(var.Name);
Console.WriteLine("屬性初始值==>"+var.GetValue(obj, null));
var.SetValue(obj, "嘗試動(dòng)態(tài)實(shí)例化設置屬性", null);
Console.WriteLine("變更后的屬性值==>"+var.GetValue(obj, null));
}
}
//調用實(shí)例化實(shí)體的方法
MethodInfo[] meth = type.GetMethods();
Console.WriteLine("MethodInfo total=" + meth.Length);
foreach (MethodInfo var in meth)
{
if (var.Name.Equals("show"))
{
Console.WriteLine("調用實(shí)例化類(lèi)的方法");
var.Invoke(obj, null);
}
}
}
}
}
聯(lián)系客服