簡體   English   中英

使用任意參數創建委托

[英]Create a delegate with arbitrary parameters

我有一個System.Reflection.MethodInfo,並希望有一個方法創建一個代表該方法的委托(最好是一個Func <...>或一個Action <...>),給定一個實例來調用它。

理想情況下,我想要像下面的psuedo代碼:

public TDelegate GetMethod<TDelegate>(MethodInfo methodToRepresent, object instanceToInvokeOn)
{
    return (TDelegate)((parameters....) => methodToRepresent.Invoke(instanceToInvokeOn, all parameters in an object[]));
}

其中TDelegate表示所表示方法的簽名。 如果簽名不匹配,則應拋出異常。

我意識到我可能無法使用簡單的lambda表達式來實現這一點,因為它的參數類型必須在編譯時才能知道。 也許我需要從頭開始構建一個委托? 是否可以通過單獨指定其主體和參數來創建委托?

謝謝

我真的不明白你的問題。 但也許你想要這個:

public TDelegate GetMethod<TDelegate>(MethodInfo methodToRepresent, object instanceToInvokeOn)
  where TDelegate:class
{
   return (TDelegate)(object)Delegate.CreateDelegate(typeof(TDelegate), instanceToInvokeOn, methodToRepresent);
}

您可以使用以下方法執行此操作。 請注意,您無法使用此方法創建通用的Action<...>因為正如您所說,這些類型在編譯時是未知的。 但這會讓你非常接近。

public delegate void DynamicInvokeDelegate(params object[] args);

public static DynamicInvokeDelegate CreateDynamicInvokeDelegate(MethodInfo method, object instance) {
    return args => method.Invoke(instance, args);
}

如果您需要委托返回值:

public delegate object DynamicInvokeWithReturnDelegate(params object[] args);

public static DynamicInvokeWithReturnDelegate CreateDynamicInvokeWithReturnDelegate(MethodInfo method, object instance) {
    return args => method.Invoke(instance, args);
}

編輯:

它實際上看起來你可能想要這個代碼:

public static T GetDelegate<T>(MethodInfo method, object instance)
    where T : class
{
    return (T)(object)Delegate.CreateDelegate(typeof(T), instance, method);
}

(object)強制轉換是必需的,因為編譯器不允許您將Delegate為任何隨機類型,並且您不能將T約束為委托。 通過對象的轉換滿足編譯器。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM