簡體   English   中英

創建返回類型不可用的委托

[英]Creating Delegates of an unavailable return type

假設我們在類型“ SomeType”中有一個靜態方法“ Instance”

MethodInfo instanceMethod = SomeType.GetMethod("Instance");

該方法返回的對象類型在我的代碼中不可用,因為它沒有引用定義該類的程序集。

然后,我想將其轉換為“對象”

像這樣:

Delegate.CreateDelegate(typeof(Func<object>), null, "Instance")

但是,我得到此異常: System.ArgumentException: Error binding to target method.

似乎正在使用CreateDelegate重載僅適用於實例方法,不適用於靜態方法。 如果傳遞MethodInfo而不是名稱"Instance" ,則將使用有效的重載

另外, Func<object>不僅與任何類型都兼容。 您可以創建一個與MakeGenericType匹配該方法的返回類型的Func<>

Type funcType = typeof(Func<>).MakeGenericType(instanceMethod.ReturnType);
Delegate del = Delegate.CreateDelegate(funcType, null, instanceMethod);

GetInstance ,我將方法命名為GetInstance而不是Instance ,以使事情更清楚。 (如果是屬性,則使用Instance是合適的)

暫無
暫無

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

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