C#泛型: Constraints

來源:互聯網
上載者:User
請看以下常式:

using System;

namespace ConsoleApplication1
{
      interface ITest
     {
            void TestMethod();
      }

      class TestType : ITest
     {
              //public testType(int i) {}
             public void TestMethod()
             {
                   Console.WriteLine("testing");
             }
   
     }
 
      
     class test
    {
         public static void Foo<T>(T t)
         where T: ITest
         {
               t.TestMethod();
         }   
    }
     class Class1
     {
            [STAThread]
            static void Main(string[] args)
           {
                  object o = new TestType();
                  Test.Foo(o); //compile-error
   
            }
      }
}

注意到那個 o對象的實際類型為TestType,繼承了ITest介面,但是編譯時間仍然報錯。也就是說對一個對象是否滿足constraints的檢查是在編譯期完成的,並不涉及到運行期的型別資訊。也就是說在C#中對泛型的執行個體化的檢查和C++中一樣,也是在編譯期就完成了。

如此一來,空添加了Constraints那樣的文法,卻完全沒有帶來任何好處,而且把泛型本身的優勢也給閹割了,實在想不到這樣做的目的何在。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.