下面是一些用於傳遞對包含字符串作爲參數的方法的引用的代碼,此問題的目的是圍繞使用泛型否定需要定義實際的類型!將方法傳遞到需要方法名稱的另一個方法
Impossible<ExampleSource, string>.Example(c => c.NonString); //does not work
Impossible<ExampleSource, string>.Example<int>(c => c.NonString); //does work
這裏的想法是讓第一個「非字符串」呼叫工作,而不必定義參數類型或聲明不可能在一個新的函數,它Func鍵< INT,TResult >。
public static void Example(Expression<Func<TSource, Func<int, TResult>>> function)
{ Process(function as MethodCallExpression); } //invalid solution...
在Java中,這可能使用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
}
}
我想我真的不明白的問題是什麼?如何使用委託? – chills42 2009-08-07 19:06:56
問題是我怎麼可以可以我推斷出T1到T4的參數類型,將代碼複製到程序中並編譯。 – bleevo 2009-08-08 00:32:19