简体   繁体   English

c#匿名类逃避内部范围块的任何方式?

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

i want to use an anonymous class but instantiate inside a using code block and have it escape the block. 我想使用一个匿名类,但在using代码块内实例化并让它逃脱阻止。 is this possible? 这可能吗?

eg, i have 例如,我有

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

And I would rather have something like: 我宁愿有类似的东西:

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

Easily done: 轻松完成:

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

But the better thing to do here is to create an actual class. 但这里更好的做法是创建一个实际的类。

Or, in C# 7, consider using a tuple. 或者,在C#7中,考虑使用元组。

Now, if you want to get really fancy... 现在,如果你想得到真正的幻想......

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 });

But this seems silly. 但这看起来很傻。 Just make a class! 刚上课!

I often write static Use methods for this purpose. 我经常为此目的编写静态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

   ...
}

Now you can just return whatever you want, even an anonymous type, and it'll always be safely wrapped in a using . 现在你可以返回任何你想要的东西,甚至是匿名类型,并且它总是被安全地包装在一个using These are very handy, for example, when working with Entity Framework. 这些非常方便,例如,在使用Entity Framework时。

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

// etc.

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM