[英]C#: Generic method expression with unknown signature
例如,我們有一個通用的方法
public void Test<T>(T param, Action<T> callback)
{
}
如果使用某個參數調用此方法,它會自動檢測T的類型,我們不需要顯式聲明它。
例如:
// here 'int' detected
Test(1, (intVariable) =>
{
});
// here 'string' detected
Test("hello", (stringVariable) =>
{
});
現在,有沒有辦法用方法做同樣的事情。 例如
Test(int.Parse, (parseMethod) =>
{
parseMethod("11");
});
是的,具有相同名稱的方法可能具有不同的簽名,並且無法檢測您要將哪一個用作參數,但可能是可能接近的。
您必須顯式轉換為Func<string, int>
才能使其工作:
Test((Func<string, int>)int.Parse, (parseMethod) =>
{
parseMethod("11");
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.