.NET泛型:是否可以对泛型类型强制执行抽象类
我有以下代码:.NET泛型:是否可以对泛型类型强制执行抽象类,.net,generics,.net,Generics,我有以下代码: void DoSomething<T>() where T : class { if(typeof(T).IsAbstract) // do something with T else // throw an error } void DoSomething(),其中T:class { if(类型为(T).IsAbstract) //用T做点什么 其他的 //出错 } 是否可以在泛型的定义中强制T是一个抽象类(类
void DoSomething<T>() where T : class
{
if(typeof(T).IsAbstract)
// do something with T
else
// throw an error
}
void DoSomething(),其中T:class
{
if(类型为(T).IsAbstract)
//用T做点什么
其他的
//出错
}
是否可以在泛型的定义中强制T是一个抽象类(类似于
其中T:abstract class
)?这是不可能的。参见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 ( )
在方法体中可以有一个保护子句:
Contract.Requires<InvalidOperationException>(!typeof(T).IsAbstract);
Contract.Requires(!typeof(T).isastract);
泛型类型声明在第一次实例化时根据泛型类型(我认为)创建的每个T参数生成一个运行时类型。由于抽象类的定义无法实例化,这两个原则直接矛盾。谢谢您的帮助!语法中不支持这一点有什么原因吗?