在下面的代码示例中,我们有一个表示房间的不可变对象的类。北,南,东和西代表进入其他房间的出口。
public sealed class Room
{
public Room(string name, Room northExit, Room southExit, Room eastExit, Room westExit)
{
this.Name = name;
this.North = northExit;
this.South = southExit;
this.East = eastExit;
this.West = westExit;
}
public string Name { get; }
public Room North { get; }
public Room South { get; }
public Room East { get; }
public Room West { get; }
}
因此,我们可以看到,该类是使用自反循环引用设计的。但是由于班级是一成不变的,所以我陷入了“鸡还是蛋”的问题。我敢肯定,经验丰富的函数式程序员知道如何处理。如何在C#中处理?
我正在努力编写一个基于文本的冒险游戏,但出于学习目的而使用功能性编程原理。我坚持这个概念,可以使用一些帮助!!!谢谢。
更新:
这是一个基于Mike Nakis关于延迟初始化的回答的有效实现:
using System;
public sealed class Room
{
private readonly Func<Room> north;
private readonly Func<Room> south;
private readonly Func<Room> east;
private readonly Func<Room> west;
public Room(
string name,
Func<Room> northExit = null,
Func<Room> southExit = null,
Func<Room> eastExit = null,
Func<Room> westExit = null)
{
this.Name = name;
var dummyDelegate = new Func<Room>(() => { return null; });
this.north = northExit ?? dummyDelegate;
this.south = southExit ?? dummyDelegate;
this.east = eastExit ?? dummyDelegate;
this.west = westExit ?? dummyDelegate;
}
public string Name { get; }
public override string ToString()
{
return this.Name;
}
public Room North
{
get { return this.north(); }
}
public Room South
{
get { return this.south(); }
}
public Room East
{
get { return this.east(); }
}
public Room West
{
get { return this.west(); }
}
public static void Main(string[] args)
{
Room kitchen = null;
Room library = null;
kitchen = new Room(
name: "Kitchen",
northExit: () => library
);
library = new Room(
name: "Library",
southExit: () => kitchen
);
Console.WriteLine(
$"The {kitchen} has a northen exit that " +
$"leads to the {kitchen.North}.");
Console.WriteLine(
$"The {library} has a southern exit that " +
$"leads to the {library.South}.");
Console.ReadKey();
}
}
Room
示例也是如此。
type List a = Nil | Cons of a * List a
。和二叉树:type Tree a = Leaf a | Cons of Tree a * Tree a
。如您所见,它们都是自引用的(递归的)。定义房间的方法如下:type Room = Nil | Open of {name: string, south: Room, east: Room, north: Room, west: Room}
。
Room
类和a 的定义有多相似List
。