Why do generics often use T?

2019-01-25 10:11发布

问题:

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<G>(){ ... }

or even

public Hello Say<Hello>(){ ... }

回答1:

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.



回答2:

T for Type, as like you said everything works fine.But putting T in that place remind you that is of generic type.



回答3:

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.



回答4:

oh, I would have thought T for Thing :)



回答5:

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.



回答6:

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



回答7:

T for Type

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



回答8:

I thought that was T for Template because it first appears in C++.