c# 匿名 class 有什么办法可以逃脱内部作用域块吗?

c# any way for an anonymous class to escape an inner scope block?

我想使用匿名 class 但在 using 代码块内实例化并让它转义该块。这可能吗?

例如,我有

using (var s = something()) {
   var instance = new { AA = s.A };
   // ... lots of code
   Console.WriteLine(instance.AA);
}

我宁愿有这样的东西:

var instance;  // <- nope, can't do this
using (var s = something()) {
   instance = new { AA = s.A };
}
// ... lots of code
Console.WriteLine(instance.AA);

轻松完成:

var instance = new { Name = default(string) };
using (whatever) 
{
  instance = new { Name = whatever.Whatever() };
}
...

但这里最好的做法是创建一个实际的 class。

或者,在 C# 7 中,考虑使用元组。

现在,如果你真的想变得很花哨...

static R Using<A, R>(A resource, Func<A, R> body) where A : IDisposable
{
    using (resource) return body(resource);
}
...

var instance = Using(something(), s => new { AA = s.A });

但这似乎很愚蠢。就做一个class!

我经常为此目的编写静态 Use 方法。

class SomethingDisposable : IDisposable {

   ...       

   public static T Use<T>(Func<SomethingDisposable, T> pFunc) {
      using (var somethingDisposable = new SomethingDisposable())
         return pFunc(somethingDisposable);
   }

   // also a version that takes an Action and returns nothing

   ...
}

现在您可以 return 任何您想要的东西,即使是匿名类型,它也将始终安全地包装在 using 中。这些非常方便,例如,在使用 Entity Framework.

var result = SomethingDisposable.Use(sd => sd.DoSomething());
var anonResult = SomethingDisposable.Use(sd => new { Property = sd.DoSomethingElse() });

// etc.