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

查看:163
本文介绍了使用一个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.

下面是它应该如何看:

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天全站免登陆