【问题标题】:Is it possible to construct anonymous/delegates like the following in C#?是否可以在 C# 中构造如下所示的匿名/委托?
【发布时间】:2016-07-13 07:19:15
【问题描述】:

有没有办法完成以下任务?这是我正在尝试做的一些简化的半伪代码:

class Foo {

  static public FUNCTION one(int foo, int bar) {    
    return List<Vector> FUNCTION(int num)  {      
      List<Vector> v = new List<Vector>();
      for (int i = 0; i < num; i++) {
        v.Add( new Vector(1+foo, 1+bar) );      
      }
      return v;
    }

  static public FUNCTION two(int foo, int bar) {    
    return List<Vector> FUNCTION(int num)  {      
      List<Vector> v = new List<Vector>();
      // Do something else?
      return v;
    }

  }    
}

那我想这样称呼它:

 generic = Foo.one(1, 2);
 List<Vector> v = generic(2);

 generic = Foo.two(1, 2);
 List<Vector> v = generic(2);

我认为这有点像我想要的,但我不确定如何传递第一组参数。

public static Func<int, int, List<Vector>> one()
{
    Func<int, List<Vector>> func = (int num) =>
    {
      List<Vector> v = new List<Vector>();
      return v;
    };
    return func;
}

【问题讨论】:

    标签: c# .net delegates anonymous-function


    【解决方案1】:

    这可以解决您的问题吗?它是一个名为Closure 的构造。它只是您已有的组合。

    public static Func<int, List<Vector>> one(int foo, int bar)
    {
        Func<int, List<Vector>> func =
            num =>
            {
                List<Vector> v = new List<Vector>();
                for (int i = 0; i < num; i++)
                {
                    v.Add(new Vector(1 + foo, 1 + bar));
                }
                return v;
            };
    
        return func;
    }
    

    【讨论】:

    • 我相信这正是我想要做的。我确实有一个问题。两个 Func 签名是否必须匹配?你可以这样做: public static Func> one(int foo, int bar) { Func> func = (num, num2) => {};返回函数; }
    • 当然不是。返回对象的类型必须与函数签名中定义的类型相同(或派生的)。您也不能从需要字符串返回值的函数返回整数。如果你想返回一个 Func&lt;int, int, List&lt;Vector&gt;&gt; 对象,只需在你的 one 函数的返回签名中定义它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-22
    • 2010-09-24
    • 1970-01-01
    相关资源
    最近更新 更多