以下代码示例为我的问题提供了上下文。
用委托初始化Room类。在Room类的第一个实现中,没有防范引发异常的委托的措施。此类异常将上升到North属性,在该North属性上评估委托(请注意:Main()方法演示了如何在客户端代码中使用Room实例):
public sealed class Room
{
private readonly Func<Room> north;
public Room(Func<Room> north)
{
this.north = north;
}
public Room North
{
get
{
return this.north();
}
}
public static void Main(string[] args)
{
Func<Room> evilDelegate = () => { throw new Exception(); };
var kitchen = new Room(north: evilDelegate);
var room = kitchen.North; //<----this will throw
}
}
考虑到我宁愿在创建对象时失败,也不愿在读取North属性时失败,所以我将构造函数更改为private,并引入了一个名为Create()的静态工厂方法。此方法捕获委托引发的异常,并引发包装异常,并具有有意义的异常消息:
public sealed class Room
{
private readonly Func<Room> north;
private Room(Func<Room> north)
{
this.north = north;
}
public Room North
{
get
{
return this.north();
}
}
public static Room Create(Func<Room> north)
{
try
{
north?.Invoke();
}
catch (Exception e)
{
throw new Exception(
message: "Initialized with an evil delegate!", innerException: e);
}
return new Room(north);
}
public static void Main(string[] args)
{
Func<Room> evilDelegate = () => { throw new Exception(); };
var kitchen = Room.Create(north: evilDelegate); //<----this will throw
var room = kitchen.North;
}
}
try-catch块是否会使Create()方法不纯?
Create
不纯,那么它也是不纯的,因为它调用了它。
Create
在获取属性时,您的函数无法防止您获取异常。如果您的代表抛出,在现实生活中很有可能仅在某些条件下才抛出。可能的情况是,在施工过程中不存在投掷的条件,但在获得财产时却存在。