我怎样才能写一个通用的匿名方法? [英] How can I write a generic anonymous method?

查看:105
本文介绍了我怎样才能写一个通用的匿名方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,我想写下:

  public Func< IList< T> ;, T> SelectElement = list => list.First(); 

但是我在 T 。我不能有一个通用的匿名方法吗?

解决方案

不,抱歉。这将需要通用字段或通用属性,这不是C#支持的功能。你可以做的最好的是做一个引入T的通用方法:

  public Func< IList< T> ;, T> SelectionMethod< T>(){return list => list.First(); } 

现在您可以说:

  Func< IList< int> ;, int> selectInts = SelectionMethod< int>(); 


Specifically, I want to write this:

public Func<IList<T>, T> SelectElement = list => list.First();

But I get a syntax error at T. Can't I have a generic anonymous method?

解决方案

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(); }

And now you can say:

Func<IList<int>, int> selectInts = SelectionMethod<int>();

这篇关于我怎样才能写一个通用的匿名方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆