首页 > 解决方案 > 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 可以具有不同的签名,并且无法检测到您想将哪个用作参数,但可能有一些接近的可能。

标签: c#.netgenericslambdageneric-programming

解决方案


您必须显式强制转换Func<string, int>才能使这项工作:

Test((Func<string, int>)int.Parse, (parseMethod) =>
{
    parseMethod("11");
});

推荐阅读