æ¡å¼µã¡ã½ããã«ãããã§ã¼ã³ã¡ã½ãã
ãµã¨ãMSDNãã¬ã¸ã³ã®è¨äºãèªãã§ãããç®ã«ä»ãã¾ããããã¼ãã³ã°ã«ã¼ã«æ±ºãã¦usingã§å¦çãå ¥ãæ¿ãã¨ãåºæ¥ãããªæ°ããã¾ããããããªããã¼ãªã®ã§ã¡ãã£ã¨ãã¡ããªï¼(^^;
using System; using System.Collections.Generic; using System.Collections; using System.Linq; using System.Text; class Block : IDisposable { static Stack<Block> stack = new Stack<Block>(); ArrayList list = new ArrayList(); public ArrayList List { get { return list; } } public Block() { stack.Push(this); } public static Block Current { get { return stack.Peek(); } } #region IDisposable Members public void Dispose() { foreach (object o in Current.List) Console.WriteLine("Unmarked:" + o); stack.Pop(); } #endregion } static class Marker { // æ¡å¼µã¡ã½ããã使ã£ããã§ã¼ã³ã¡ã½ãã public static T Mark<T>(this T target) { Block.Current.List.Add(target); return target; } } class Foo { string key; public Foo(string key) { this.key = key; } public void Bar() { Console.WriteLine("Bar:" + key); } public override string ToString() { return key; } } class Program { static void Main(string[] args) { using (new Block()) { Foo foo1 = new Foo("foo1"); // foo1ãªãã¸ã§ã¯ããBlockå ã«ãã¼ã¯ foo1.Mark().Bar(); // foo2ãªãã¸ã§ã¯ããBlockå ã«ãã¼ã¯ new Foo("foo2").Mark().Bar(); } // ãã¼ã¯ãããªãã¸ã§ã¯ããã¹ã³ã¼ãããå¤ããã®ã§unmarkedã表示ããã } } /* çµæ Bar:foo1 Bar:foo2 Unmarked:foo1 Unmarked:foo2 */
æ¡å¼µã¡ã½ããã«ããã«ã¯éçã¯ã©ã¹ã§ãªããã°ãªãããIDisposeæ å½ã¨æ¡å¼µã¡ã½ããæ å½ã®ï¼ã¤ã®ã¯ã©ã¹ãä½ãå¿ è¦ãããã®ãè¯ããªãã§ããã»ã»ã»
ã¾ãã¡ãã£ã¨ãããã¿ã¨ãããã¨ã§ã