使用IEnumerable< T>作为委托返回类型 [英] Using an IEnumerable<T> as a delegate return type

查看:88
本文介绍了使用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;作为委托返回类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆