【发布时间】:2014-05-23 18:13:28
【问题描述】:
你知道比下面更好的方法(更漂亮)来抛出异常吗?
public long GetPlaylistId(long songInPlaylistId)
{
var songInPlaylist = service.GetById(songInPlaylistId);
return songInPlaylist
.With(x => x.Playlist)
.ReturnValueOrException(x => x.Id,
new ArgumentException(
"Bad argument 'songInPlaylistId'"));
}
一元扩展方法:
public static TResult With<TInput, TResult>(this TInput obj,
Func<TInput, TResult> evaluator)
where TInput : class
where TResult : class
{
return obj == null ? null : evaluator(obj);
}
public static TResult ReturnValueOrException<TInput, TResult>(
this TInput obj, Func<TInput, TResult> evaluator, Exception exception)
where TInput : class
{
if (obj != null)
{
return evaluator(obj);
}
throw exception;
}
【问题讨论】:
-
不要使用异常来控制程序的流程。当没有其他选项可以解决问题时,您应该引发异常。 msdn.microsoft.com/en-us/library/dd264997.aspx
-
@Tim Schmelter,我认为在这种情况下我必须抛出异常。对于您的意见,我可以回报什么?
-
@Neshta:一种方法:返回
Nullable<long>,另一种方法:TryGetPlaylistId使用out参数和bool作为返回值。 -
在您希望参数有效的情况下抛出异常是完全可以接受的。例如,如果文件不存在,使用
new FileStream(filename, FileMode.Open);会抛出FileNotFoundException异常。 -
如果建议的空传播运算符在该语言中,他可能(取决于其确切定义)
return songInPlaylist?.Playlist?.Id;。