c# - 处理 null 返回的静态方法

标签 c#

所以我创建了一个提供程序(实际上有几个),我意识到我的某些逻辑中存在一些模式。它正在重复,我认为如果我可以创建这个扩展方法,我可以删除很多代码行: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/

相关文章:

c# - Azure 身份验证 Web 应用本地主机回复 url

c# - 尝试使用 linq 在第一次匹配后获取所有元素

c# - 使用 SqlBulkCopy 插入数据时出错

c# - 最好是在接口(interface)上嵌入依赖关系,还是让具体的类来完成这项工作?

c# - 如何将主窗口设置为不可见以在 WPF 中将图像显示为主窗口

c# - 使用 WPF 在 C# 中动态更改图像

C# 反射 : Get info for all members of class and base classes

c# - Windows phone7 : Open a webpage on button click?

c# - 使用 iText 阅读 PDF 批注

c# - XML 序列化 : 64Bit Windows7, oct 处理器核心,32GB RAM 和 OutOfMemory 异常