使用IEnumerable< T>作为委托返回类型

编程入门 行业动态 更新时间:2024-10-13 20:21:37
本文介绍了使用IEnumerable< T>作为委托返回类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在尝试定义一个将返回IEnumerable的委托函数。我有几个问题 - 我想我很接近,但需要一些帮助,到达那里...

I'm trying to define a delegate function that will return an IEnumerable. I'm having a couple issues - I think I'm close, but need some help getting there...

我可以定义我的委托人罚款:

I can define my delegate fine:

public delegate IEnumerable<T> GetGridDataSource<T>();

现在怎么用?

// I'm sure this causes an error of some sort public void someMethod(GetGridDataSource method) { method(); }

这里?

myObject.someMethod(new MyClass.GetGridDataSource(methodBeingCalled));

感谢提示。

推荐答案

您需要在someMethod声明中指定一个通用类型参数。

you need to specify a generic type parameter in your "someMethod" declaration.

: $ b

Here's how it should look:

public void someMethod<T>(GetGridDataSource<T> method) { method(); }

当您调用该方法时,不需要指定类型参数,因为它将从您传入的方法推断,所以调用将如下所示:

When you call the method you won't need to specify the type parameter because it will be inferred from the method that you pass in, so the call will look like this:

myObject.someMethod(myObject.methodBeingCalled);

这是一个完整的例子,您可以粘贴到VS并尝试:

Here's a full example you can paste into VS and try out:

namespace DoctaJonez.StackOverflow { class Example { //the delegate declaration public delegate IEnumerable<T> GetGridDataSource<T>(); //the generic method used to call the method public void someMethod<T>(GetGridDataSource<T> method) { method(); } //a method to pass to "someMethod<T>" private IEnumerable<string> methodBeingCalled() { return Enumerable.Empty<string>(); } //our main program look static void Main(string[] args) { //create a new instance of our example var myObject = new Example(); //invoke the method passing the method myObject.someMethod<string>(myObject.methodBeingCalled); } } }

更多推荐

使用IEnumerable&lt; T&gt;作为委托返回类型

本文发布于:2023-11-09 04:24:37,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1571397.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:类型   amp   IEnumerable   gt   lt

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!