C#泛型:约束T,其中T:对象不编译;错误:约束不能特殊类“对象” [英] C# Generics: Constraining T where T : Object doesn't compile; Error: Constraint cannot be special class 'object'
问题描述
当我限制T搭配:这样的对象:
公共接口IDoWork< T>其中T:对象
{
牛逼的DoWork();
}
我得到的错误:
约束不能特殊类对象
这是否意味着存在与不编译下面的一个隐含的区别是什么?
公共接口IDoWork< T> //其中T:对象
{
牛逼的DoWork();
}
有两个约束之间没有区别,不同的是一个是不允许为是没用的,明确的状态。
在C#4.0语言规范(10.1.5类型参数约束)说的两件事是:
该类型不能为对象。由于所有类型都派生自object, 这样的约束没有效果,如果它被允许
...
如果T没有主要约束或类型参数约束,其 有效基类为对象。
在你的评论,你说你是试图使 T
是类型虚空
的。 虚空
是一种特殊类型,表示没有返回类型,并且可以代替 T
的不能使用,这就要求相应的具体类型。你必须创建你的方法和 T
版本的空隙版本,如果你想两者兼而有之。
When I constrain T with : Object like this:
public interface IDoWork<T> where T : Object
{
T DoWork();
}
I get the error:
Constraint cannot be special class 'object'
Does that mean there is an implied difference with the following that does compile?
public interface IDoWork<T> // where T : Object
{
T DoWork();
}
There is no difference between the two constraints, except for that one is disallowed for being useless to explicitly state.
The C# 4.0 language specification (10.1.5 Type parameter constraints) says two things about this:
The type must not be object. Because all types derive from object, such a constraint would have no effect if it were permitted.
...
If T has no primary constraints or type parameter constraints, its effective base class is object.
In your comment, you said that you were trying to make T
be of type Void
. Void
is a special type that indicates that there is no return type and cannot be used in place of T
, which requires an appropriate concrete type. You will have to create a void version of your method and a T
version if you want both.
这篇关于C#泛型:约束T,其中T:对象不编译;错误:约束不能特殊类“对象”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!