開發(fā)時有時會遇到一些需要實例化指定名稱的類,這個時候要用到反射來實現(xiàn)了??梢詤⒄障旅娴目刂婆_示例:
需要實例化的類:
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("指定名稱實例化的類的方法");
}
}
}
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("當(dāng)前程序集:" + 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是指定的類名
//將得到的類型傳給一個新建的構(gòu)造器類型變量
ConstructorInfo constructor = type.GetConstructor(new Type[0]);
//使用構(gòu)造器對象來創(chuàng)建對象
object obj = constructor.Invoke(new Object[0]);
//輸出對象類型
Console.WriteLine(obj);
//調(diào)用實例化實體的字段
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");//設(shè)置字段的值
}
Console.WriteLine(temp.Name+"字段的值==>" + temp.GetValue(obj));
}
//調(diào)用實例化實體的屬性
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, "嘗試動態(tài)實例化設(shè)置屬性", null);
Console.WriteLine("變更后的屬性值==>"+var.GetValue(obj, null));
}
}
//調(diào)用實例化實體的方法
MethodInfo[] meth = type.GetMethods();
Console.WriteLine("MethodInfo total=" + meth.Length);
foreach (MethodInfo var in meth)
{
if (var.Name.Equals("show"))
{
Console.WriteLine("調(diào)用實例化類的方法");
var.Invoke(obj, null);
}
}
}
}
}