简体   繁体   English

C#:具有未知签名的通用方法表达式

[英]C#: Generic method expression with unknown signature

For example we have a generic method 例如,我们有一个通用的方法

public void Test<T>(T param, Action<T> callback)
{

}

If call this method with some parameter, it automatically detect the type of T and we don't need to declare it explicitly. 如果使用某个参数调用此方法,它会自动检测T的类型,我们不需要显式声明它。

For example: 例如:

// here 'int' detected
Test(1, (intVariable) =>
{

});

// here 'string' detected
Test("hello", (stringVariable) =>
{

});

Now, is there any possible way to do the same with methods. 现在,有没有办法用方法做同样的事情。 For example 例如

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

Yes, method/s with the same name can have different signatures and it's impossible to detect which one you want to use as a parameter, but maybe something close possible. 是的,具有相同名称的方法可能具有不同的签名,并且无法检测您要将哪一个用作参数,但可能是可能接近的。

You have to explicitly cast to Func<string, int> to make this work: 您必须显式转换为Func<string, int>才能使其工作:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM