DLL类库:
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectTestLib
{
public class ReflectTest
{
public ReflectTest()
{ }
public string WriteString(string s)
{
return "欢迎您," + s;
}
public static string WriteName(string s)
{
return "欢迎您光临," + s;
}
public string WriteNoPara()
{
return "您使用的是无参数方法";
}
}
}
反射类实现:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectTestLib
{
public class ReflectTest
{
public ReflectTest()
{ }
public string WriteString(string s)
{
return "欢迎您," + s;
}
public static string WriteName(string s)
{
return "欢迎您光临," + s;
}
public string WriteNoPara()
{
return "您使用的是无参数方法";
}
}
}
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectTest
{
class Program
{
static void Main(string[] args)
{
System.Reflection.Assembly ass;
Type type;
object obj;
try
{
ass = System.Reflection.Assembly.LoadFile(@"D:\工作区\Reflection\ReflectTestLib\bin\Release\ReflectTestLib.dll");
type = ass.GetType("ReflectTestLib.ReflectTest");//必须使用名称空间+类名称
System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
obj = ass.CreateInstance("ReflectTestLib.ReflectTest");//必须使用名称空间+类名称
string s = (string)method.Invoke(obj, new string[] { "实例方法的调用" }); //实例方法的调用
Console.WriteLine(s);
method = type.GetMethod("WriteName");//方法的名称
s = (string)method.Invoke(null, new string[] { "静态方法的调用" }); //静态方法的调用
Console.WriteLine(s);
method = type.GetMethod("WriteNoPara");//无参数的实例方法调用
s = (string)method.Invoke(obj, null);
Console.WriteLine(s);
method = null;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
ass = null;
type = null;
obj = null;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ReflectTest
{
class Program
{
static void Main(string[] args)
{
System.Reflection.Assembly ass;
Type type;
object obj;
try
{
ass = System.Reflection.Assembly.LoadFile(@"D:\工作区\Reflection\ReflectTestLib\bin\Release\ReflectTestLib.dll");
type = ass.GetType("ReflectTestLib.ReflectTest");//必须使用名称空间+类名称
System.Reflection.MethodInfo method = type.GetMethod("WriteString");//方法的名称
obj = ass.CreateInstance("ReflectTestLib.ReflectTest");//必须使用名称空间+类名称
string s = (string)method.Invoke(obj, new string[] { "实例方法的调用" }); //实例方法的调用
Console.WriteLine(s);
method = type.GetMethod("WriteName");//方法的名称
s = (string)method.Invoke(null, new string[] { "静态方法的调用" }); //静态方法的调用
Console.WriteLine(s);
method = type.GetMethod("WriteNoPara");//无参数的实例方法调用
s = (string)method.Invoke(obj, null);
Console.WriteLine(s);
method = null;
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
finally
{
ass = null;
type = null;
obj = null;
}
}
}
}
技术改变命运!