我想知道为什么不编译?
public static void Main(string[] args)
{
using (MyStruct sss = new MyStruct())
{
sss.s = "fsdfd";// Cannot modify members of 'sss' because it is a 'using variable'
//sss.Set(12); //but it's ok
}
}
public struct MyStruct : IDisposable
{
public int n;
public string s;
public void Set(int n)
{
this.n = n;
}
public void Dispose()
{
Console.WriteLine("dispose");
}
}
Run Code Online (Sandbox Code Playgroud)
更新:但它完美无缺.为什么?
public static void Main(string[] args)
{
using (MyClass sss = new MyClass())
{
sss.Field = "fsdfd"; …Run Code Online (Sandbox Code Playgroud) 我知道在同步世界中第一个片段是正确的,但是WaitAsync和async/await magic是什么?请给我一些.net内部.
await _semaphore.WaitAsync();
try
{
// todo
}
finally
{
_semaphore.Release();
}
Run Code Online (Sandbox Code Playgroud)
要么
try
{
await _semaphore.WaitAsync();
// todo
}
finally
{
_semaphore.Release();
}
}
Run Code Online (Sandbox Code Playgroud) 我对以下代码有一些疑问:
using System;
namespace ConsoleApplication2
{
public struct Disposable : IDisposable
{
public void Dispose() { }
}
class Program
{
static void Main(string[] args)
{
using (Test()) { }
}
static Disposable Test()
{
return new Disposable();
}
}
}
Run Code Online (Sandbox Code Playgroud)
我的问题是:
Disposable结构进行操作的using语句是否会从Test()结构框中返回?为了试图找出自己,我检查了上面代码生成的IL,这里是Main(...)方法的IL :
.method private hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 1
.locals init (
[0] valuetype ConsoleApplication2.Disposable CS$3$0000)
L_0000: call valuetype ConsoleApplication2.Disposable ConsoleApplication2.Program::Test()
L_0005: stloc.0
L_0006: …Run Code Online (Sandbox Code Playgroud) c# ×3
.net ×2
idisposable ×2
using ×2
async-await ×1
boxing ×1
locking ×1
semaphore ×1
struct ×1