我有以下類型層次:如何讓C#Create.Delegate支持繼承?
public abstract class Parent { }
public class Child : Parent
{
public Task SayAsync(string arg)
{
Console.WriteLine(arg);
return Task.CompletedTask;
}
}
我需要實現以下目標:
- 在運行時創建的
Parent
任何實例(這已經通過調用Func<Parent>
我得到解決 - 然後調用(在該實例中)所有的
public
方法(它總是返回Task
並接受string
作爲參數)傳入arg
這不是一個常數。
在熱通道上面存在因此,爲了提高性能,我訴諸Cached Delegates
所以在啓動我將創建代表我會再緩存並在需要時使用。
這裏是我已經明確地爲Child
做了一個例子,但我不知道如何讓委託接受Parent
(因爲我不知道編譯時的類型)。
// If I change Child to Parent, I get "Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type"
private delegate Task Invoker(Child instance, string arg);
void Main()
{
var instance = new Child(); // This will be obtained by calling a Func<Parent>
var methodWithArg = instance.GetType().GetMethod("SayAsync");
var func = GetDelegateWithArg(methodWithArg);
func(instance, "Foo");
}
private static Invoker GetDelegateWithArg(MethodInfo method)
{
object pointer = null;
return (Invoker)Delegate.CreateDelegate(typeof(Invoker), pointer, method);
}
任何想法或替代方案,以幫助我實現目標,表示讚賞。
這是真棒!事實上,我設法通過將程序集標記爲'[assembly:SecurityTransparent]'從[HERE](http://stackoverflow.com/a/5160513/1226568)中獲取補償額外開銷,它現在比'Delegate'更快。 CreateDelegate'版本:-) – MaYaN