所以我创建了一个提供程序(实际上有几个),我意识到我的某些逻辑中存在一些模式。它正在重复,我认为如果我可以创建这个扩展方法,我可以删除很多代码行:D
所以,基本上发生的事情是这样的:
// Get our item to be deleted
var model = await this._service.GetAsync(id);
// If we have nothing, throw an error
if (model == null)
throw new HttpException(404, string.Format(Resources.GenericNotFound, "List item"));
现在,我在很多地方都这样做,不仅仅是为了删除,而是为了更新。 我想创建一个扩展方法,允许我做这样的事情:
// Get our item to be deleted
var model = await this._service.GetAsync(id).ThowIfNull("List item");
我还需要它来处理任何返回类型。所以在这种情况下,它可能是一个Account,但是会有一个供应商也有这个代码返回一个Order,但我需要扩展方法来为两者工作。
我认为这里的挑战是异步位,但我可能错了!
有人知道这是否可行吗?
最佳答案
避免 async-await 部分的一种可能性是使扩展方法在 Task
内部返回的类型上工作
public static T ThrowIfNull<T>(this T obj, string message) where T : class
{
if (obj == null)
throw new HttpException(404, string.Format(Resources.GenericNotFound, message));
return obj;
}
我将扩展方法设为通用,因为我不知道是什么类型 model
是。然后你就可以像这样使用它了。
var model = (await this._service.GetAsync(id)).ThrowIfNull("List item");
通过输入 await
在括号中,您确保它将等待任务并在将结果传递给扩展方法之前将其解包。
另一种选择是使扩展方法适用于 Task<T>
public static async Task<T> ThrowIfNullAsync<T>(this Task<T> task, string message)
where T : class
{
var obj = await task;
if (obj == null)
throw new HttpException(404, string.Format(Resources.GenericNotFound, message));
return obj;
}
而且您不需要括号。
var model = await this._service.GetAsync(id).ThrowIfNullAsync("List item");
但这意味着异常现在包含在任务中,根据您使用此方法的方式,这可能是理想的,也可能不是理想的。
关于c# - 处理 null 返回的静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39273868/