Constrain type parameter of a method to the interfaces implemented by another type
The intention开发者_StackOverflow of the following is to only allow the call IRegistration<Foo>.As<IFoo>
if Foo
implements IFoo
:
interface IRegistration<TImplementation>
{
void As<TContract>() where TImplementation : TContract;
}
This is not allowed by the C# 3.0 compiler. I get the following error:
'SomeNamespace.IRegistration.As()' does not define type parameter 'TImplementation'
Is there some way around this, other than putting both type parameters in the method declaration?
This question is inspired by this other question about Autofac.
You are trying to add a constraint on a type parameter that does not exist in the type parameter list.
Is this what you meant?
interface IRegistration<TImplementation> where TImplementation : TContract
{
void As<TContract>();
}
Though this will not compile either - you can't have a generic constraint on a generic type.
This will compile, though will probably not produce the constraint you want on the method itself:
interface IRegistration<TImplementation,TContract> where TImplementation : TContract
{
void As<TContract>();
}
See if this will do:
interface IRegistration<TImplementation,TContract> where TImplementation : TContract
{
void As();
}
This way, any time you use TImplementation
, it will be constrained to be a TContract
and you can still use TContract
in the As
method.
You can find more information here - look at the section towards the end of the page, titled "Type Parameters as Constraints".
精彩评论