开发时有时会遇到一些需要实例化指定名称的类,这个时候要用到反射来实现了。可以参照下面的控制台示例:
需要实例化的类:
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("当前程序集:" + 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是指定的类名
//将得到的类型传给一个新建的构造器类型变量
ConstructorInfo constructor = type.GetConstructor(new Type[0]);
//使用构造器对象来创建对象
object obj = constructor.Invoke(new Object[0]);
//输出对象类型
Console.WriteLine(obj);
//调用实例化实体的字段
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));
}
//调用实例化实体的属性
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, "尝试动态实例化设置属性", null);
Console.WriteLine("变更后的属性值==>"+var.GetValue(obj, null));
}
}
//调用实例化实体的方法
MethodInfo[] meth = type.GetMethods();
Console.WriteLine("MethodInfo total=" + meth.Length);
foreach (MethodInfo var in meth)
{
if (var.Name.Equals("show"))
{
Console.WriteLine("调用实例化类的方法");
var.Invoke(obj, null);
}
}
}
}
}