C#语言:泛型,打开/关闭,绑定/未绑定,构造

ath*_*hos 39 c# generics

我正在阅读Anders Hejlsberg等的第4版"C#编程语言"一书.

有几个定义有点扭曲:

未绑定的泛型类型:泛型类型声明本身表示未绑定的泛型类型...

构造类型:包含至少一个类型参数的类型称为构造类型.

open type:open类型是一种涉及类型参数的类型.

闭合类型:闭合类型是不是开放类型的类型.

unbound type:指非泛型类型或非绑定泛型类型.

bound类型:指非泛型类型或构造类型.[annotate] ERIC LIPPERT:是的,非泛型类型被认为是绑定和未绑定的.

问题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
Run Code Online (Sandbox Code Playgroud)

问题2,书中说"未绑定类型是指由类型声明声明的实体.未绑定泛型类型本身不是类型,它不能用作变量,参数或返回值的类型,或者一个基本类型.唯一可以引用未绑定泛型类型的构造是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>(); }
}
Run Code Online (Sandbox Code Playgroud)

Hei*_*nzi 25

这些是未绑定泛型类型的示例:

  • 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
}
Run Code Online (Sandbox Code Playgroud)

  • @athos:海因兹是对的.进一步澄清.T和U是类型*参数*,它们是*声明*.然后可以将它们*用作类型参数,或者仅用作类型.通过类比,假设你有:`int foo(int x){return bar(x); 这里"x"是声明它的foo*的*参数,以及使用它的bar*的调用的*参数.类型参数和类型参数的工作方式类似 (4认同)

naw*_*fal 5

乔恩(Jon)在这里给出了一个很好的答案

由于链接的答案中的所有内容都很完美,因此没有提供技术描述。仅在这里复制要点作为答案,它看起来像:

A                             //non generic, bound
A<U, V>                       //generic,     bound,  open,   constructed
A<int, V>                     //generic,     bound,  open,   constructed
A<int, int>                   //generic,     bound,  closed, constructed
A<,> (used like typeof(A<,>)) //generic,     unbound 
Run Code Online (Sandbox Code Playgroud)

与海因兹讨论后编辑