![](/img/trans.png)
[英]IEnumerable<T> having the same type as the return value of delegate
[英]Using an IEnumerable<T> as a delegate return type
我正在尝试定义一个将返回 IEnumerable 的委托函数。 我有几个问题 - 我想我已经接近了,但需要一些帮助才能到达那里......
我可以很好地定义我的委托:
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”声明中指定一个泛型类型参数。
这是它的外观:
public void someMethod<T>(GetGridDataSource<T> method)
{
method();
}
当您调用该方法时,您不需要指定类型参数,因为它将从您传入的方法中推断出来,因此调用将如下所示:
myObject.someMethod(myObject.methodBeingCalled);
这是一个完整的示例,您可以将其粘贴到 VS 中并试用:
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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.