首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用块中的对象初始化器生成警告CA 2000的代码分析?

使用块中的对象初始化器生成警告CA 2000的代码分析?
EN

Stack Overflow用户
提问于 2018-02-11 04:11:47
回答 1查看 0关注 0票数 0

以下是代码:

代码语言:txt
复制
    using (var control = new ReCaptchaControl()
    {
        ID = id,
        Theme = theme,
        SkipRecaptcha = false
    })
    {
        // Do something here
    }

代码分析是:

代码语言:txt
复制
    using (var control = new ReCaptchaControl())
    {
        control.ID = id;
        control.Theme = theme;
        control.SkipRecaptcha = false; 

        // Do something here
    }

这两个代码块有什么区别?

EN

Stack Overflow用户

发布于 2018-02-11 13:29:34

不,这是有区别的。

代码语言:txt
复制
Foo x = new Foo { Bar = "Baz" };

相当于:

代码语言:txt
复制
Foo tmp = new Foo();
tmp.Bar = "Baz";
Foo x = tmp;
代码语言:txt
复制
using System;

public class ThrowingDisposable : IDisposable
{
    public string Name { get; set; }

    public string Bang { set { throw new Exception(); } }

    public ThrowingDisposable()
    {
        Console.WriteLine("Creating");
    }

    public void Dispose()
    {
        Console.WriteLine("Disposing {0}", Name);
    }
}

class Test
{
    static void Main()
    {
        PropertiesInUsingBlock();
        WithObjectInitializer();
    }

    static void PropertiesInUsingBlock()
    {
        try
        {
            using (var x = new ThrowingDisposable())
            {
                x.Name = "In using block";
                x.Bang = "Ouch";
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Caught exception");
        }
    }

    static void WithObjectInitializer()
    {
        try
        {
            using (var x = new ThrowingDisposable
            {
                Name = "Object initializer",
                Bang = "Ouch"
            })
            {
                // Nothing
            }
        }
        catch (Exception)
        {
            Console.WriteLine("Caught exception");
        }
    }
}

输出

代码语言:txt
复制
Creating
Disposing In using block
Caught exception
Creating
Caught exception
票数 0
EN
查看全部 1 条回答
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100007381

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档