有时候由于项目结构的原因,会出现相互引用的情况,我们知道C#是不支持相互引用的,这时间如果要引用另外的类,就必须使用反射。
C#的反射方法很简单:
string bll = AppDomain.CurrentDomain.BaseDirectory + @"bin\要引用的dll全名(带.dll文件名)";//dll文件路径
var asm = System.Reflection.Assembly.LoadFile(bll);//加载dll
var type = asm.GetType("要引用的dll名(不带.dll文件名)");//获取dll类型
var instance = asm.CreateInstance("要引用的dll名(不带.dll文件名)");//实例化dll
//var method = type.GetMethods()[2];//选择要调用的方法
var method = type.GetMethod("InsertBillInfoByReflection");//也可以具体到方法名称
object[] parameters = { BillType.ReturnBill, model, billIndexID, dbHelper, error };//初始传参
bool b = (bool)method.MakeGenericMethod(typeof(T)).Invoke(instance, parameters);//调用方法
if (b)
{
billIndexID = (int)parameters[2];//返回参数
}
else
{
error = (string)parameters[4];//返回参数
}
return b;实例图:
