我最近做了一个公司的评估,该公司有一个案例,他们想要将谓词设置为方法的输入参数。几乎没有经验,我一直在研究它。代码如下:
using System;
public interface IBird
{
Egg Lay();
}
public class Chicken : IBird
{
public Chicken()
{
}
public void EggLay()
{
}
public Egg Lay()
{
return new Egg();
}
}
public class Egg
{
public Egg(Func<IBird> createBird)
{
throw new NotImplementedException("Waiting to be implemented.");
}
public IBird Hatch()
{
throw new NotImplementedException("Waiting to be implemented.");
}
}
public class Program
{
public static void Main(string[] args)
{
// var chicken1 = new Chicken();
// var egg = chicken1.Lay();
// var childChicken = egg.Hatch();
}
}
我的问题是Egg函数的期望是什么以及为什么?
我已经看过this answer和this answer以及this answer,但它仍然没有任何意义。这是学术上的,但我真的很想了解。
public Egg(Func<IBird> createBird)
不是一个函数,它是constructor类的Egg
。由于Egg
类必须Hatch
鸟类,它需要创造鸟类。 Func<IBird>
是一个委托,即代表方法参考的值。在这个特定的情况下,它代表一个factory method。谓词将是返回布尔值的方法或委托。通过此参数,您可以传递任何创建IBird
s的方法。由于IBird
接口没有指定鸟的显式实现,因此可以使用不同的方法初始化Egg
,从而创建不同的鸟类型。有些需要构造函数参数,有些则不需要。
你会像这样实现Egg
public class Egg
{
private readonly Func<IBird> _createBird;
public Egg(Func<IBird> createBird)
{
_createBird = createBird; // No "()". createBird is not called, just assigned.
}
public IBird Hatch()
{
return _createBird(); // Here createBird is called, therefore the "()".
}
}
现在,Hatch
方法可以通过_createBird
代表的中间体创建鸟类,而无需了解如何或哪种类型的鸟类创建。
你会怎么创造一个鸡蛋?那么,首先你需要一些鸟类实施例如:
public class BlackBird : IBird
{
... your implementation goes here
}
然后你需要一个创建并返回IBird
的方法。例如。:
IBird CreateBlackBird()
{
return new BlackBird();
}
然后你可以创建一个鸡蛋
var egg = new Egg(CreateBlackBird); // No "()". CreateBlackBird is not called but referenced.
IBird newBird = egg.Hatch();
确保传递没有参数列表的方法,即没有括号,因为你不想在此时调用CreateBlackBird
方法,你想将它传递给构造函数,在那里它存储在私有字段_createBird
中以后用过。
lambda表达式动态创建一个匿名委托:
var egg = new Egg(() => new BlackBird());
() => new BlackBird()
是一个lambda表达式。它相当于CreateBlackBird
方法。返回类型未指定,并且是从Egg
构造函数的参数类型推断出来的。它没有名字。方法标题中仅保留参数括号。 =>
替换了return
关键字。
在使用颜色作为构造函数参数实现了一个额外的鸟类之后,您可以编写
var egg = new Egg(() => new ColoredBird(Color.Blue));
也可以看看:
谢谢你的这个例子。您可以实现单例模式,以便通过修改Egg类可以只孵化一次,如下所示:
public class Egg
{
private readonly Func<IBird> _createBird;
private IBird _Bird = null;
public Egg(Func<IBird> createBird)
{
_createBird = createBird;
}
public IBird Hatch()
{
if (_Bird == null)
{
_Bird = _createBird();
}
return _Bird;
}
}
您可以实现单例模式,以便通过修改Egg类如下,鸟只能孵化一次。
public interface IBird
{
Egg Lay();
}
public class Egg
{
private readonly Func<IBird> _createBird;
private bool _hatched;
public Egg(Func<IBird> createBird)
{
_createBird = createBird;
}
public IBird Hatch()
{
if (_hatched)
Console.WriteLine("Egg are already hatched");
_hatched = true;
Console.WriteLine("Egg are hatched now;");
Console.ReadKey();
return _createBird();
}
}
public class Chicken : IBird
{
public Egg Lay()
{
var egg = new Egg(() => new Chicken());
return egg;
}
}
public class Program
{
public static void Main(string[] args)
{
var chicken1 = new Chicken();
var egg = chicken1.Lay();
var childChicken = egg.Hatch();
}
}