none
擴充方法跟Start()簽名相同問題 RRS feed

  • 問題

  • 下面著個thread.Start();的Start()應該是擴充方法吧?  但是我之前學的擴充方法跟本來就有的舊方法相同就不會執行? 像擴充方法擴充ToString不會執行擴充的ToString?

         class Program
        {
            private object _lock1 = new object();
            private object _lock2 = new object();
            public void Function1()
            {
                Console.WriteLine("Function1啟動,執行緒:{0}",Thread.CurrentThread.ManagedThreadId);
                lock (_lock1)
                {
                    Thread.Sleep(1000);
                    lock (_lock2)
                    {
                        //DoNothing
                    }
                }
                Console.WriteLine("執行緒:{0}退出", Thread.CurrentThread.ManagedThreadId);
            }
            public void Function2()
            {
                Console.WriteLine("Function2啟動,執行緒:{0}", Thread.CurrentThread.ManagedThreadId);
                lock (_lock1)
                {
                    Thread.Sleep(2000);
                    lock (_lock2)
                    {
                        //DoNothing
                    }
                }
                Console.WriteLine("執行緒:{0}退出", Thread.CurrentThread.ManagedThreadId);
            }
            static void Main(string[] args)
            {
                Program sample = new Program();
                Thread[] threads = new Thread[2] { new Thread(sample.Function1), new Thread(sample.Function2) };
                threads.Start();
                Console.ReadLine();
            }
        }
        public static class Test
        {
            public static void Start(this Array array)
            {
                foreach (Object obj in array)
                {
                    Thread thread = obj as Thread;
                    if (thread != null)
                    {
                        thread.Start();
                    }
                }
            }
        }

    另外是問個問題,上面的foreach.......如果改成下面這個有差別嗎?為什麼要特地宣告Object再把它轉成Thread類型?

                foreach (Thread thread in array)
                {
                    if (thread != null)
                    {
                        thread.Start();
                    }
                }

    謝謝

    2011年11月15日 上午 09:06

解答

所有回覆