在 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 关键字。这是取自文档的示例:
//using System.Collections;
//using System.Diagnostics;
public static void Process()
{
// Display powers of 2 up to the exponent of 8:
foreach (int number in Power(2, 8))
{
Debug.Write(number.ToString() + " ");
}
// Output: 2 4 8 16 32 64 128 256
}
public static IEnumerable Power(int baseNumber, int highExponent)
{
int result = 1;
for (int counter = 1; counter <= highExponent; counter++)
{
result = result * baseNumber;
yield return result;
}
}
C# yield 似乎是从迭代方法返回中间结果的方式,而不是 Ruby 在运行时将整个代码块直接标记到指定区域的方式。
是否有类似的技术可以使用 yield 关键字在 C# 中编写更少的代码?例如:
public class EntityBase
{
// Generic Try-Catch function, so we never have to write this block in our code
public object GenericTryCatch()
{
try
{
// yield here
}
catch(Exception except)
{
Logger.log(except.Message);
}
finally
{
// return the control to the caller function
}
return null;
}
}