我在网上做了很多搜索,除了将实例重新转换回派生类以访问这些事件之外,真的没有找到任何具体的东西。
因此,通过使用扩展方法,我向 DbDataAdapter 抽象类添加了两个新方法,这将允许为这两个特定事件添加事件处理程序,这是我的实现(编辑于 2013 年 4 月 23 日,用于处理实例或静态处理程序方法):
using System;
using System.Data.Common;
using System.Reflection;
namespace Extensions
{
/// <summary>
/// Delegate event handler used with the <c>DbDataAdapter.RowUpdated</c> event.
/// </summary>
public delegate void RowUpdatedEventHandler(object sender, RowUpdatedEventArgs e);
/// <summary>
/// Delegate event handler used with the <c>DbDataAdapter.RowUpdating</c> event.
/// </summary>
public delegate void RowUpdatingEventHandler(object sender, RowUpdatingEventArgs e);
public static class DbDataAdapterExtension
{
private static EventInfo GetEvent(string eventName, Type type)
{
return type.GetEvent(eventName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
}
/// <summary>
/// Registers a <c>RowUpdatedEventHandler</c> with this instance's <c>RowUpdated</c> event.
/// </summary>
/// <param name="handler">The event handler to register for the event.</param>
/// <returns><c>true</c> if the event handler was successfully registered, otherwise <c>false</c>.</returns>
public static bool AddRowUpdatedHandler(this DbDataAdapter adapter, RowUpdatedEventHandler handler)
{
EventInfo updEvent = GetEvent("RowUpdated", adapter.GetType());
if (updEvent != null)
{
try
{
if (handler.Method.IsStatic)
{
updEvent.AddEventHandler(adapter, Delegate.CreateDelegate(updEvent.EventHandlerType, handler.Method));
}
else
{
updEvent.AddEventHandler(adapter, Delegate.CreateDelegate(updEvent.EventHandlerType, handler.Target, handler.Method));
}
return true;
}
catch { }
}
return false;
}
/// <summary>
/// Registers a <c>RowUpdatingEventHandler</c> with this instance's <c>RowUpdating</c> event.
/// </summary>
/// <param name="handler">The event handler to register for the event.</param>
/// <returns><c>true</c> if the event handler was successfully registered, otherwise <c>false</c>.</returns>
public static bool AddRowUpdatingHandler(this DbDataAdapter adapter, RowUpdatingEventHandler handler)
{
EventInfo updEvent = GetEvent("RowUpdating", adapter.GetType());
if (updEvent != null)
{
try
{
if (handler.Method.IsStatic)
{
updEvent.AddEventHandler(adapter, Delegate.CreateDelegate(updEvent.EventHandlerType, handler.Method));
}
else
{
updEvent.AddEventHandler(adapter, Delegate.CreateDelegate(updEvent.EventHandlerType, handler.Target, handler.Method));
}
return true;
}
catch { }
}
return false;
}
}
}
我将基本 RowUpdatedEventArgs 和 RowUpdatingEventArgs 用于返回给委托的事件参数,因此如果您需要特定于提供程序的成员,这些成员只能通过从上述两个基本事件参数类派生的提供程序定义的类获得,然后他们将需要被强制转换为这些类。否则,它可以正常工作,现在我可以从 DbDataAdapter 类中获得独立于提供程序的事件处理程序(这是 Microsoft 应该从一开始就实现它们的方式)。
干杯!