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 关注
- 140 浏览
添加回答
举报