【问题标题】:Using an IEnumerable<T> as a delegate return type使用 IEnumerable<T> 作为委托返回类型
【发布时间】:2009-07-08 18:14:25
【问题描述】:

我正在尝试定义一个将返回 IEnumerable 的委托函数。我有几个问题 - 我想我已经很接近了,但需要一些帮助才能到达那里......

我可以很好地定义我的委托:

 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));

感谢您的提示。

【问题讨论】:

    标签: c# asp.net delegates c#-3.0


    【解决方案1】:

    您需要在 "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);
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2010-09-27
      • 2022-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多