有可能创建一个引用泛型方法的Func对象吗?像LINQ OrderBy:
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
    this IEnumerable<TSource> source,
    Func<TSource, TKey> keySelector
)
Dan*_*Tao 20
如果我理解正确,那么你问是否可以在匿名方法中引用泛型方法.
答案是肯定的.
例如,假设您想要一些以排序顺序Func返回IEnumerable<int>对象元素的(确切地说OrderBy<int, int>).你可以这样做:
Func<IEnumerable<int>, Func<int, int>, IOrderedEnumerable<int>> orderByFunc =
    System.Linq.Enumerable.OrderBy<int, int>;
然后你可以Func像其他任何一样使用它:
int[] ints = new int[] { 1, 3, 5, 4, 7, 2, 6, 9, 8 };
// here you're really calling OrderBy<int, int> --
// you've just stored its address in a variable of type Func<...>
foreach (int i in orderByFunc(ints, x => x))
    Console.WriteLine(i);
输出:
1
2
3
4
5
6
7
8
9
另一方面,如果你问是否可以创建一个"通用匿名方法",如下所示:
Func<T> getDefault<T> = () => default(T);
那么这取决于你的背景.这可以在T已经声明为泛型类型参数的上下文中完成- 即,在泛型类或泛型方法中.(参见Freddy Rios的回答.)不幸的是,在这样的背景之外,这是非法的.
| 归档时间: | 
 | 
| 查看次数: | 16328 次 | 
| 最近记录: |