现在的位置: 首页 > 综合 > 正文

C#泛型: Constraints

2012年11月18日 ⁄ 综合 ⁄ 共 821字 ⁄ 字号 评论关闭
请看以下例程:

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那样的语法,却完全没有带来任何好处,而且把泛型本身的优势也给阉割了,实在想不到这样做的目的何在。

抱歉!评论已关闭.