相关疑难解决方法(0)

使用带有null对象的语句

using在(可能)null对象上使用该语句是否安全?
请考虑以下示例:

class Test {
    IDisposable GetObject(string name) {
        // returns null if not found
    }

    void DoSomething() {
        using (IDisposable x = GetObject("invalid name")) {
            if (x != null) {
                 // etc...
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

是否保证Dispose只有在对象不为空时才会被调用,而且我不会得到一个NullReferenceException

c# idisposable using

168
推荐指数
3
解决办法
3万
查看次数

在using块中使用'as IDisposable'

编辑:我的问题不是关于使用块及其工作原理.我的问题是关于两种方法的区别,如下所示.

我正在阅读CQRS旅程指南,我不明白这行代码:

using (repo as IDisposable)
Run Code Online (Sandbox Code Playgroud)

那是什么意思?为什么将它用作IDisposable?在典型的使用块中,不需要将其用作IDisposable:

using (var repo = this.respositoryFactory()) { // ... }
Run Code Online (Sandbox Code Playgroud)

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

这是代码出现的方法:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

c# idisposable using

3
推荐指数
1
解决办法
772
查看次数

标签 统计

c# ×2

idisposable ×2

using ×2