Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/24.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# 将关键字yield转换为Ruby之类的代码块摘要_C#_.net_Syntax - Fatal编程技术网

C# 将关键字yield转换为Ruby之类的代码块摘要

C# 将关键字yield转换为Ruby之类的代码块摘要,c#,.net,syntax,C#,.net,Syntax,在Ruby中,我们可以从其他作用域生成代码块,以优化编写代码的量: def get_resource(published=true) find_resources do if I18n.locale == :ar && @resource_slug == "home" Resource.find_by_slug("home") else ResourceType.find_by_slug(@type_slug).

在Ruby中,我们可以从其他作用域生成代码块,以优化编写代码的量:

  def get_resource(published=true)
    find_resources do
      if I18n.locale == :ar && @resource_slug == "home"
        Resource.find_by_slug("home")
      else
        ResourceType.find_by_slug(@type_slug).resources.send(
          published ? :published : :unpublished
        ).find_by_slug(@resource_slug)
      end
    end
  end

  def get_resources(published=true)
    find_resources do
      ResourceType.includes(:resources).find_by_slug(@type_slug).resources.send(
        published ? :published : :unpublished
      )
    end
  end

  def find_resources
    begin
      @type_slug, @resource_slug = params[:type], params[:resource]
      yield
    rescue Mongoid::Errors::DocumentNotFound, NoMethodError
      nil
    end
  end
在C#中,我们还有yield关键字。以下是一个例子:


我不知道Ruby,但看起来基本上你想要传递“一些要执行的代码”——这通常是在C#中通过委托(或者接口,当然是特定意义上的委托)完成的。就我所见,Ruby中的
yield
与C#中的
yield-return
完全不同。如果没有任何参数或返回值,则
操作
委托是合适的。然后,可以使用任何方法调用该方法来创建委托,例如:

  • 通过方法组转换或显式委托创建表达式创建的现有方法
  • lambda表达式
  • 匿名方法
例如:

Foo(() => Console.WriteLine("Called!"));

...


static void Foo(Action action)
{
    Console.WriteLine("In Foo");
    action();
    Console.WriteLine("In Foo again");
    action();
}

关于代表还有很多需要学习的地方——不幸的是,我现在没有时间详细讨论,但我建议你找一本关于C#的好书,从中了解他们。(特别是,它们可以接受参数和返回值这一事实在各种情况下都是至关重要的,包括LINQ)。

我对Ruby的有限知识告诉我,您只需要某种委托:

void SomeMethod(Action action) {
    // do some stuff here
    action(); // the equivalent (that I can see) of yield
}
用法:

SomeMethod(() => {
    // method that is called when execution hits "action()" above
});

谢谢你的解释和建议。这部作品应该因为发现了Jon Skeet不知道的东西而获奖;-)
void SomeMethod(Action action) {
    // do some stuff here
    action(); // the equivalent (that I can see) of yield
}
SomeMethod(() => {
    // method that is called when execution hits "action()" above
});