2 回答

TA貢獻2012條經驗 獲得超12個贊
如果您知道像 Func 這樣的函數類型,則可以直接將其轉換為如下所示
private static void InvokeFunctionDynamically<T>(T data)
{
//1. Define the delegate
Func<string, bool, T> genericFunction = (name, isEnabled) =>
{
if(isEnabled)
{
return data;
}
return default(T);
};
// 2. demonstrate that the delegate is retrieved at the run time as an object
object runtimeObject = genericFunction;
//3. Cast it directly to the delegate type
var result =((Func<string, bool, T>) runtimeObject)("hello", true);
Console.WriteLine($"Result {result}");
}
結果如下:
- 2 回答
- 0 關注
- 169 瀏覽
添加回答
舉報