What is this syntax: "Component.For<IOutput>()"?
I'm finding code examples all over the place in IoC and DI discussions that use <
and >
in their syntax, usually at the end of what looks like a method call.
Can someone
- Tell me what language this is, and
- Explain this syntax enough to help me understand the code examples, so I can make sure I understand the underlying principles.
The angle brackets are used to denote the type to use. It ensures compile time safety. This is the syntax used for generics (c#).
They are part of the generics support in the framework. They allow you to specify a type as part of the method (or class). They are referred to as type parameters.
For instance you can have a strongly typed list, which relies upon you telling it what type it should accept:
List<string> myList;
Allows it to accept types of string
in the Add
function. The class definition for this would look something like:
public class List<T>
{
public void Add(T item)
{
}
}
When you created the List you told it to expect a type of string
. This is the type parameter T
in the above class. In the method Add
it expects an instance of type T
(in this instance a string). Which means when you call Add
on a List<string>
, Add
expects a string
to be supplied.
Similarly if you created:
List<bool> myOtherList;
The Add
method would expect a bool
parameter not a string
parameter.
1.) The language looks like C#, but without reference/context I can't be 100% sure.
2.) Assuming C#, this syntax is used with generics.
精彩评论