Generic constraints in C#, T is the same TSomethingElse, right?
I often see:
public interface IFoo<TWidget> where TWidget : ISomethingElse { }
In this case, TWidget is the same as using the generic T, correct? I'm finding this surprisingly hard to google or find in the specs. I'm 99% sure that T + any other characters is 开发者_Python百科the same as saying just T, but wanted to be absolutely sure.
The name of the generic type parameter can by any valid identifier name.
In most documentation you would indeed find T
where you put TWidget
.
From MSDN:
Do name generic type parameters with descriptive names, unless a single letter name is completely self explanatory and a descriptive name would not add value.
In this case TWidget is generic, but not because it is T+something. Although it is recommended to name it T+something, it can be anything you want, as long as it syntactically correct type identifier name.
As you suspect, it's perfectly legal to put any identifier where you usually see T
.
You'll often see more descriptive names when there are constraints put on the generic type, usually indicating what the constraint might be. It's also helpful to have a longer identifier when you have multiple generic type parameters, so you can easily remember which one is which.
The Type parameter can be names anything but the standard way of doing it is to use T and then go through the alphabet as more generic types are required.
So you might have public interface IFoo<T, U> where T : ISomethingElse { }
But you could just as easily use public interface IFoo<Banana, Spiggot>
. It really doesn't matter
精彩评论