反射(Reflection)是.NET中的重要机制,通过放射,可以在运行时获得.NET中每一个类型(包括类、结构、委托、接口和枚举等)的成员,包括方法、属性、事件,以及构造函数等。还可以获得每个成员的名称、限定符和参数等。有了反射,即可对每一个类型了如指掌。如果获得了构造函数的信息,即可直接创建对象,即使这个对象的类型在编译时还不知道。
1.加载程序集:
public static Assembly
LoadAssemblyFile(
string assPath)
{
Assembly assembly = Assembly.LoadFile(assPath);
return assembly;
}
2.获取一个程序集中的所有类
public static Type[]
GetClassInfo(
string dllPath)
{
Type[] tps = LoadAssemblyFile(dllPath).GetTypes();
return tps;
}
3获取一个类中的所有方法
public static MethodInfo[]
GetMethods(Type tpe)
{
MethodInfo[] metInfo = tpe.GetMethods();
return metInfo;
}
4.获取类中的属性
public static PropertyInfo[]
GetAttributes(Type tpe,
string perName =
null)
{
PropertyInfo[] perInfos = tpe.GetProperties();
if (perName ==
null)
{
perInfos =
new PropertyInfo[] { tpe.GetProperty(perName) };
}
return perInfos;
}
5.判断是否集成某个接口,或者某个类
public static bool IsParent(Type itpe, Type clsType)
{
Type[] tpes = clsType.GetInterfaces();
if (itpe.IsInterface)
{
foreach (
var nextpe
in tpes)
{
if (itpe == nextpe)
{
return true;
}
}
}
else
{
do
{
if (clsType.BaseType == itpe)
{
return true;
}
clsType = clsType.BaseType;
}
while (
true);
}
return false;
}
6.实例化一个对象
public static T CreateInstance<T>(
string fullName,
string assemblyName)
{
string path = fullName +
"," + assemblyName;
Type o = Type.GetType(path);
object obj = Activator.CreateInstance(o,
true);
return (T)obj;
}
7.通过反射来执行方法
public static void ExecuteMethod(Type tpe,
string methodName,
object[] parms)
{
if (tpe==
null)
{
throw new Exception(
"tpe 值不能为Null");
}
MethodInfo metInfo = tpe.GetMethod(methodName);
object obj = Activator.CreateInstance(tpe, parms);
if (parms!=
null && parms.Length>
0)
{
metInfo.Invoke(obj, parms);
}
else
{
metInfo.Invoke(obj,
null);
}
}
转载请注明原文地址: https://ju.6miu.com/read-970190.html