如何编写通用的匿名方法? [英] How can I write a generic anonymous method?
本文介绍了如何编写通用的匿名方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
具体来说,我想写这个:
Specifically, I want to write this:
public Func<IList<T>, T> SelectElement = list => list.First();
但我在 T
处遇到语法错误.我不能有一个通用的匿名方法吗?
But I get a syntax error at T
. Can't I have a generic anonymous method?
推荐答案
不,抱歉.这将需要通用字段或通用属性,而 C# 不支持这些功能.你能做的最好的事情就是创建一个引入 T 的泛型方法:
Nope, sorry. That would require generic fields or generic properties, which are not features that C# supports. The best you can do is make a generic method that introduces T:
public Func<IList<T>, T> SelectionMethod<T>() { return list => list.First(); }
现在你可以说:
Func<IList<int>, int> selectInts = SelectionMethod<int>();
这篇关于如何编写通用的匿名方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文