bug*_*ixr 2 c# asp.net delegates c#-3.0
我正在尝试定义一个将返回IEnumerable的委托函数.我有几个问题 - 我想我很接近,但需要一些帮助才能到达那里......
我可以定义我的代表罚款:
public delegate IEnumerable<T> GetGridDataSource<T>();
Run Code Online (Sandbox Code Playgroud)
现在怎么用呢?
// I'm sure this causes an error of some sort
public void someMethod(GetGridDataSource method) {
method();
}
Run Code Online (Sandbox Code Playgroud)
和这里?
myObject.someMethod(new MyClass.GetGridDataSource(methodBeingCalled));
Run Code Online (Sandbox Code Playgroud)
谢谢你的提示.
您需要在"someMethod"声明中指定泛型类型参数.
这是它应该看起来的样子:
public void someMethod<T>(GetGridDataSource<T> method)
{
method();
}
Run Code Online (Sandbox Code Playgroud)
当您调用该方法时,您不需要指定type参数,因为它将从您传入的方法中推断出来,因此调用将如下所示:
myObject.someMethod(myObject.methodBeingCalled);
Run Code Online (Sandbox Code Playgroud)
这是一个完整的示例,您可以粘贴到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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1752 次 |
| 最近记录: |