gpt4 book ai didi

c# - 在 using block 中使用 'as IDisposable'

转载 作者:行者123 更新时间:2023-11-30 13:22:40 25 4
gpt4 key购买 nike

编辑:我的问题不是关于 using block 及其工作原理。我的问题是关于这两种方法的区别,如下所示。

我正在阅读 CQRS Journey Guide,但我不明白这行代码:

using (repo as IDisposable)

这是什么意思?为什么将它用作 IDisposable?在典型的 using block 中,不需要将其用作 IDisposable:

using (var repo = this.respositoryFactory()) { // ... }

知道为什么作者用第一种方式而不是第二种方式写它吗?

这是出现该代码的方法:

private Conference.Web.Public.Models.Conference GetConference(string conferenceCode)
{
var repo = this.repositoryFactory();
using (repo as IDisposable)
{
var conference = repo.Query<Conference>()
.First(c => c.Code == conferenceCode);
var conferenceModel =
new Conference.Web.Public.Models.Conference
{
Code = conference.Code,
Name = conference.Name,
Description = conference.Description
};
return conferenceModel;
}
}

最佳答案

Any idea why the authors wrote it the first way instead of the second way?

这通常是由于对语言特性的误解。您编写它的方式是用 C# 编写它的惯用方式:

using (var repo = this.respositoryFactory()) 
{

作者方法的唯一真正优势是如果 repositoryFactory可能会返回一个不实现 IDisposable 的类型.通过 using (repo as IDisposable) 编写代码,相同的代码可以处理非一次性类型。

大多数时候,这不是问题。然而,工厂可以有选择地返回IDisposable。类型。例如,假设此方法是在泛型类中完成的,并且 repositoryFactory返回了 IRepository<T> , type 可能实现也可能不实现 IDiposable 是可能的。 ,在这种情况下,这种方法可以处理这两种情况,而无需强加 IDisposable。对泛型类型的约束。

关于c# - 在 using block 中使用 'as IDisposable',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20011148/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com