简体   繁体   中英

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.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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