c# - C#:具有未知签名的通用方法表达式
问题描述
例如我们有一个泛型方法
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");
});
是的,具有相同名称的方法/s 可以具有不同的签名,并且无法检测到您想将哪个用作参数,但可能有一些接近的可能。
解决方案
您必须显式强制转换Func<string, int>
才能使这项工作:
Test((Func<string, int>)int.Parse, (parseMethod) =>
{
parseMethod("11");
});
推荐阅读
- c# - Web api 只返回一些字段
- reactjs - 如果特定动态页面在反应中不可用,如何重定向到 404
- excel - VBA代码用另一张纸上的单元格值替换公式的一部分
- java - 减少在同一地点连续取货/送货的服务时间
- formatting - 如何使用 oh-my-zsh 使我在 ZSH 中输入的命令变为粗体?
- javascript - 为什么我的代码无法通过 Javascript 中从字符串中删除空格的测试?
- c++ - 完美转发函数参数到函数指针:值传递呢?
- ios - Swift 崩溃与 nil 合并运算符 EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000000
- ios - Xcode 提示“已达到您的最大 App ID 限制”和“Xcode 找不到任何 iOS 应用开发配置文件”
- javascript - JavaScript 评估速记问题