Covariance not working with generic dictionary entry
Given the class below:
public class ConcreteEmployeeRoleCreator<T, TConcrete, TSpec>
where TConcrete : class, T, new()
where T : EmployeeRole
where TSpec : EmployeeRoleSpecification
{
public ConcreteEmployeeRoleCreator(TSpec spec) { Specification = spec; }
public TSpec Specification { get; private set;开发者_开发问答 }
public T Create() { return new TConcrete(); }
}
I would like to have a dictionary of 'creators', but I haven't been able to work out how to do it yet. If I try and define the dictionary using the lowest common denominator types, the compiler is not allowing an instance to be added
[Test]
public void Creator_CanCreateFromSpec() {
var creators = new Dictionary<string, ConcreteEmployeeRoleCreator<EmployeeRole, EmployeeRole, EmployeeRoleSpecification>>();
var spec = new SalesmanRoleSpecification();
var creator = new ConcreteEmployeeRoleCreator<EmployeeRole, Salesman, SalesmanRoleSpecification>(spec);
creators.Add("salesman", creator); <==== ** compile error **
}
Salesman is an EmployeeRole, and SalesmanRoleSpecification is an EmployeeRoleSpecification (or I wouldn't be able to define the creator above without a compiler error as well).
SO I guess it is the way I am declaring the dictionary? What am I doing wrong?
Cheers,
BerrylGeneric covariance has to be specified at the declaration of the covariant type - and it can only be specified for interfaces and delegates.
So, given that you're using a class, a
ConcreteEmployeeRoleCreator<EmployeeRole, Salesman, SalesmanRoleSpecification>
will never be a
ConcreteEmployeeRoleCreator<EmployeeRole, EmployeeRole, EmployeeRoleSpecification>
You'll need to look for an alternative approach. To be honest, by the time you get to three type parameters and want two of them to be covariant, you've got a pretty hard-to-understand design to start with, I'm afraid :(
精彩评论