我使用反射做一些數據庫查詢和創建委託加快使用反射一點我已經在下面的錯誤絆倒:錯誤時結合泛型方法的委託 - 簽名或安全透明
Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type.
我有兩種創建這些委託的方法,它們都具有相似的結構,但一個可以工作,另一個不可以。它們之間唯一的主要區別是不工作的參數有更多的參數,並且返回帶有泛型類型的List,因爲工作參數只接受單個參數並返回聲明類型的單個值而不是泛型T 。
下面是一些示例代碼:
的方法
public List<T> GetConnections<T>(IElement element, bool getChildren, bool getParents) where T : IConnectionTable, new()
{
// do some database stuff and return a List<T> where the constraints on
// T follow the method description above.
}
創建代表
簡化爲清楚起見
private Func<IElement, bool, bool, List<IConnectionTable>> GetConnectionsDelegate(string connectionType)
{
// Get the type element from the passed string.
Type elementType = Type.GetType(connectionType, true);
// Create the generic method using that type.
MethodInfo method = typeof(MyClass).GetMethod("GetConnections", new Type[]{ typeof(IElement), typeof(bool), typeof(bool) });
MethodInfo generic = method.MakeGenericMethod(elementType);
// Create a delegate of the method to speed up subsequent queries.
var converted = (Func<IElement, bool, bool, List<IConnectionTable>>)Delegate.CreateDelegate(typeof(Func<IElement, bool, bool, List<IConnectionTable>>), this, generic);
// the above line is where it dies
}
實際的代碼保存委託到一個私有的靜態辭典,所以我只需要使用一次反射。
如果我打印出方法的內容和通用這一切似乎都正確轉換。
Result StandardOutput:
System.Collections.Generic.List`1[T] GetConnections[T](MyProject.Database.IElement, Boolean, Boolean)
System.Collections.Generic.List`1[MyTestProject.TestConnection] GetConnections[TestConnection](MyProject.Database.IElement, Boolean, Boolean)
我在這裏的假設是,問題在於VS IConnectionTable列表返回值類型的泛型列表之間的差別,使得該方法在許多鑄造錯誤的泛型方法返回一個非泛型列表的結果,是反正有點不對。另外,測試時代碼運行良好。
它不應該是私人和公共方法的差異爲我的其他委託創建方法是一樣的,做工精細(我也嘗試改變GetConnectionsDelegate公衆並沒有什麼區別。)
任何幫助將不勝感激。
NDH
您是否正在創建代表以加快一些反射開銷,而不是真正的db查詢? –
是的,這是加速反思。我想這與代碼本身做什麼並不重要。 –
謝謝。那麼,有時把它放到透視圖中可能會有用...... –