我正在尝试定义一个将返回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< T>作为委托返回类型
发布评论