在項目開發中,我們有時候難免會用到第三方公司的dll文件,如果我們直接引用,會提高開發效率,但會增加項目與第三方公司的dll耦合度,不利於後續的項目升級。
這個時候用反射無疑是最好的解決辦法,反射調用方法獲取屬性,這個網上的文章很多,可以自行百度。但是反射註冊自定義事件或者調用委託很少,我在網上找到的例子大多是基於EventHandler的事件,所以這裏我與大家分享一下
這裏自己做了一個小demo
工程部分代碼
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string fullPath2 = AppDomain.CurrentDomain.BaseDirectory + "\\ConsoleApplication2.dll";
System.Reflection.Assembly assembly2 = System.Reflection.Assembly.LoadFile(fullPath2);
object objInstance = assembly2.CreateInstance("ConsoleApplication2.CustomerClass");
//獲得事件
EventInfo eInfo = objInstance.GetType().GetEvent("CustomerEvent");
Type handlerType = eInfo.EventHandlerType;
//事件觸發時的方法
MethodInfo inf = typeof(Program).GetMethod("cc_CustomerEvent");
Delegate d0 = Delegate.CreateDelegate(handlerType, inf);
//註冊事件
eInfo.AddEventHandler(objInstance, d0);
//調用方法觸發事件
MethodInfo method = objInstance.GetType().GetMethod("WriteStr");
method.Invoke(objInstance, null);
Console.ReadKey();
}
public static void cc_CustomerEvent(object sender, object attribute)
{
//獲得事件中提供的對象屬性
PropertyInfo info = attribute.GetType().GetProperty("name");
if (info.GetValue(attribute,null) != null)
{
Console.WriteLine(info.GetValue(attribute, null));
}
}
}
}
第三方dll,自定義委託事件
namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
}
}
public class CustomerClass
{
public delegate void CustomerEventHandler(object sender, Student str);
public event CustomerEventHandler CustomerEvent;
public CustomerClass(){ }
public void WriteStr()
{
Student stu = new Student();
stu.name = "張三";
CustomerEvent(null, stu);
}
}
public class Student
{
public Student() { }
public string _name = string.Empty;
public string name
{
get { return _name; }
set { _name = value; }
}
}
}