Below is some code that is used to pass around a reference to a method that contains strings as parameters, the purpose of this question is around using generics to negate the need to define the actual type!
Impossible<ExampleSource, string>.Example(c => c.NonString); //does not work
Impossible<ExampleSource, string>.Example<int>(c => c.NonString); //does work
The idea here is to make the first "NonString" call work without having to define the parameter type or declare a new function in Impossible that takes Func<int, TResult>.
public static void Example(Expression<Func<TSource, Func<int, TResult>>> function)
{ Process(function as MethodCallExpression); } //invalid solution...
In Java this could be achieved using Func<?, TResult>
public class Impossible<TSource, TResult>
{
public static void Example(Expression<Func<TSource, Func<TResult>>> function)
{ Process(function as MethodCallExpression); }
public static void Example(Expression<Func<TSource, Func<string, TResult>>> function)
{ Process(function as MethodCallExpression); }
public static void Example(Expression<Func<TSource, Func<string, string, TResult>>> function)
{ Process(function as MethodCallExpression); }
public static void Example<T1>(Expression<Func<TSource, Func<T1, TResult>>> function)
{ Process(function as MethodCallExpression); }
public static void Example<T1, T2>(Expression<Func<TSource, Func<T1, T2, TResult>>> function)
{ Process(function as MethodCallExpression); }
private static void Process(MethodCallExpression exp)
{
if (exp == null) return;
Console.WriteLine(exp.Method.Name);
}
}
public class ExampleSource
{
public string NoParams() { return ""; }
public string OneParam(string one) { return ""; }
public string TwoParams(string one, string two) { return ""; }
public string NonString(int i) { return ""; }
}
public class Consumer
{
public void Argh()
{
Impossible<ExampleSource, string>.Example(c => c.NoParams);
Impossible<ExampleSource, string>.Example(c => c.OneParam);
Impossible<ExampleSource, string>.Example(c => c.TwoParams);
Impossible<ExampleSource, string>.Example<int>(c => c.NonString);
Impossible<ExampleSource, string>.Example(c => c.NonString); //MAKE THIS WORK
}
}