代码之家  ›  专栏  ›  技术社区  ›  Remus

.NET泛型:是否可以对泛型类型强制使用抽象类

  •  2
  • Remus  · 技术社区  · 14 年前

    我有以下代码:

    void DoSomething<T>() where T : class
    {
        if(typeof(T).IsAbstract)
             // do something with T
        else
             // throw an error
    }
    

    有没有可能在泛型的定义中强制T是一个抽象类(比如 where T : abstract class )?

    2 回复  |  直到 14 年前
        1
  •  4
  •   jason    14 年前

    这是不可能的。参见C规范的第10.1.5条。特别是,语法清楚地表明这是不可能的。

    type-parameter-constraints-clauses:
        type-parameter-constraints-clause
        type-parameter-constraints-clauses   type-parameter-constraints-clause
    type-parameter-constraints-clause:
        where   type-parameter   :   type-parameter-constraints
    type-parameter-constraints:
        primary-constraint
        secondary-constraints
        constructor-constraint
        primary-constraint   ,   secondary-constraints
        primary-constraint   ,   constructor-constraint
        secondary-constraints   ,   constructor-constraint
        primary-constraint   ,   secondary-constraints   ,   constructor-constraint
    primary-constraint:
        class-type
        class
        struct
    secondary-constraints:
        interface-type
        type-parameter
        secondary-constraints   ,   interface-type
        secondary-constraints   ,   type-parameter
    constructor-constraint
        new   (   )
    

    在方法体中可以有一个guard子句:

    Contract.Requires<InvalidOperationException>(!typeof(T).IsAbstract);
    
        2
  •  0
  •   Tom W    14 年前

    泛型类型声明在第一次实例化时根据泛型类型(我认为)创建的每个T参数生成一个运行时类型。由于抽象类的定义不能被实例化,这两个原则直接矛盾。