以下是代码:
using (var control = new ReCaptchaControl()
{
ID = id,
Theme = theme,
SkipRecaptcha = false
})
{
// Do something here
}
代码分析是:
using (var control = new ReCaptchaControl())
{
control.ID = id;
control.Theme = theme;
control.SkipRecaptcha = false;
// Do something here
}
这两个代码块有什么区别?
发布于 2018-02-11 13:29:34
不,这是有区别的。
Foo x = new Foo { Bar = "Baz" };
相当于:
Foo tmp = new Foo();
tmp.Bar = "Baz";
Foo x = tmp;
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");
}
}
}
输出
Creating
Disposing In using block
Caught exception
Creating
Caught exception
https://stackoverflow.com/questions/-100007381
复制相似问题