我正在尝试定义一个将返回 IEnumerable 的委托(delegate)函数。我遇到了几个问题 - 我想我已经接近了,但需要一些帮助才能到达那里......
我可以很好地定义我的委托(delegate):
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);
}
}
}
关于c# - 使用 IEnumerable<T> 作为委托(delegate)返回类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1099729/