我正在阅读 Anders Hejlsberg 等人撰写的《C# 编程语言》第 4 版。
有几个定义有点曲折:
未绑定(bind)的泛型类型:泛型类型声明本身表示未绑定(bind)的泛型类型......
构造类型:至少包含一个类型参数的类型称为构造类型。
开放类型:开放类型是涉及类型参数的类型。
封闭类型:封闭类型是一种非开放类型。
未绑定(bind)类型:指非泛型类型或未绑定(bind)泛型。
绑定(bind)类型:指非泛型类型或构造类型。 [注释] ERIC LIPPERT:是的,非泛型类型被认为是绑定(bind)和未绑定(bind)的。
问题 1,下面我列出的是正确的吗?
int //non-generic, closed, unbound & bound,
class A<T, U, V> //generic, open, unbound,
class A<int, U, V> //generic, open, bound, constructed
class A<int, int, V> //generic, open, bound, constructed
class A<int, int, int> //generic, closed, bound, constructed
问题 2,书上说 “未绑定(bind)类型是指由类型声明声明的实体。 未绑定(bind)泛型类型本身不是类型,它不能用作变量、参数或返回值的类型,也不能用作基类型。 唯一可以在其中引用未绑定(bind)泛型类型的构造是 typeof 表达式(第 7.6.11 节)。” 很好,但下面是一个可以编译的小测试程序:
public class A<W, X> { }
// Q2.1: how come unbounded generic type A<W,X> can be used as a base type?
public class B<W, X> : A<W, X> { }
public class C<T,U,V>
{
// Q2.2: how come unbounded generic type Dictionary<T, U> can be used as a return value?
public Dictionary<T,U> ReturnDictionary() { return new Dictionary<T, U>(); }
// Q2.3: how come unbounded generic type A<T, U> can be used as a return value?
public A<T, U> ReturnB() { return new A<T, U>(); }
}
最佳答案
这些是未绑定(bind)泛型类型的示例:
-
List<>
-
Dictionary<,>
它们可以与 typeof
一起使用,即以下是有效的表达式:
-
typeof(List<>)
-
typeof(Dictionary<,>)
这应该可以回答您的问题 2。关于问题 1,请注意类型参数 可以是构造类型 或类型参数。因此,您的列表应更新如下:
public class MyClass<T, U> { // declares the type parameters T and U
// all of these are
// - generic,
// - constructed (since two type arguments are supplied), and
// - bound (since they are constructed):
private Dictionary<T, U> var1; // open (since T and U are type parameters)
private Dictionary<T, int> var2; // open (since T is a type parameter)
private Dictionary<int, int> var3; // closed
}
关于C# Language : generics, open/closed, bound/unbound, constructed,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6607033/