Why do generics often use T?

前端 未结 8 867
故里飘歌
故里飘歌 2020-12-17 18:08

Is there any reason for the use of \'T\' in generics? Is it some kind of abbreviation? As far as I know, everything works. For example

public G Say         


        
相关标签:
8条回答
  • 2020-12-17 18:16

    If your generic type represents something special, you can make it more precise.. Usually prefixing it with T : IRepository<TEntity>, SomeCollection<TItem, TComparer> ..

    0 讨论(0)
  • 2020-12-17 18:22

    T for Type

    Also, E is used for Element that's very common too. You're right G also works.

    0 讨论(0)
  • 2020-12-17 18:23

    T is for Type. But it's really just a tradition and there is nothing to prevent you from using other names. For example, generic dictionaries use <TKey, TValue>.

    There is also a Microsoft guideline that recommends using the letter T if you have a single type parameter, and prefix descriptive parameter names with T if you have more than one. Doing so will provide a more consistent feel across your code.

    0 讨论(0)
  • 2020-12-17 18:28

    There might also be a bit of tradition too as C++ templates use T most of the time, and generics are similar in function to C++'s templates, when used for generic programming.

    0 讨论(0)
  • 2020-12-17 18:31

    oh, I would have thought T for Thing :)

    0 讨论(0)
  • 2020-12-17 18:32

    It's just a shorthand like I is conventionally used for interfaces in .NET, and in other environments C is sometimes used for classes (Delphi uses this, IIRC).

    Generally "T" on its own means "the single type parameter in this context" and if you have multiple type parameters, they get a T prefix, e.g. Dictionary<TKey, TValue>. It just makes it obvious when you're reading the code that it's a type parameter rather than a specific concrete type.

    0 讨论(0)
提交回复
热议问题