Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C#中是否可以像下面这样构造匿名/委托?_C#_.net_Delegates_Anonymous Function - Fatal编程技术网

在C#中是否可以像下面这样构造匿名/委托?

在C#中是否可以像下面这样构造匿名/委托?,c#,.net,delegates,anonymous-function,C#,.net,Delegates,Anonymous Function,是否有任何方法可以完成以下任务?下面是一些我试图做的简化半伪代码: 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++)

是否有任何方法可以完成以下任务?下面是一些我试图做的简化半伪代码:

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

  }    
}
class-Foo{
静态公共函数1(intfoo,intbar){
返回列表函数(int num){
列表v=新列表();
for(int i=0;i
那么我想这样称呼它:

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

 generic = Foo.two(1, 2);
 List<Vector> v = generic(2);
generic=Foo.one(1,2);
列表v=通用(2);
通用=Foo.two(1,2);
列表v=通用(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;
}
public static Func one()
{
Func Func=(int num)=>
{
列表v=新列表();
返回v;
};
返回函数;
}

这是你问题的解决方案吗?它是一个叫做
闭包的结构。它只是你已经拥有的东西的组合

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;
}
publicstaticfuncone(intfoo,intbar)
{
Func Func=
num=>
{
列表v=新列表();
for(int i=0;i
我相信这正是我想要做的。不过我有一个问题。两个Func签名必须匹配吗?你能做类似的事情吗:公共静态Func one(int foo,int bar){Func Func=(num,num2)=>{};return Func;}当然不能。返回对象的类型必须相同(或派生对象)与函数签名中定义的相同。也不能从需要字符串返回值的函数返回整数。如果要返回
Func
对象,只需在
one
函数的返回签名中定义即可。