What code allows me to have this syntax ClassName<datatype>()
I noticed that the Ninject API has calls such as
Bind<ISomething>().DoSomethingElse();
How is thi开发者_如何转开发s achieved?
This is called method chaining. This achieved by building methods that are returing the same instances.
simple example
interface test
{
test bind();
test DoSomethingElse();
}
class tester:test
{
test bind()
{
// blah
}
test DoSomethingElse()
{
// blah
}
}
tester obj = new tester()
obj.bind().DoSomethingElse()
What's happening here is that Bind
is a generic method which takes a single type parameter. It's signature would look like the following
public T Bind<T>() {
...
}
So calling Bind<ISomething>()
calls the function with a bound type parameter of ISomething
and returns an ISomething
instance.
Note: I don't know if this is the actual signature of the function. Not familiar with Ninject in particular but speculating based on other APIs
It's called Generics.
In your specific example, it is a Generic Method.
The idea is that you only have to write one generic method signature which you can use for any type (as long as you don't restrict it).
Take the generic List<T>
for example. You can create it to hold any type: string, int, classes, structs, whichever you like. If it wasn't generic, you'd have to write specific code for all of the types it can contain, or everything would have to be boxed to an object, like with the ArrayList
class, which comes at a performance penalty.
It's a generic method defined on the BindingRoot
class.
public IBindingToSyntax<T> Bind<T>()
{
...
}
精彩评论