I am trying to ignore the implementation of the interface by providing a factory / builder using generics. However, I run into a problem with multiple dispatchers and C # generators at runtime, which does something strange.
Main scenario: I defined several interfaces:
public interface IAddressModel { } public interface IUserModel { }
Then I have a factory class to return the actual implementations:
public class Factory { public T BuildModel<T>() { return BuildModel(default(T)); } public object BuildModel(object obj) {
The problem is that the factory is invoked as follows: new Factory().BuildModel<IAddressModel>() The BuildModel (...) method, which is dispatched at runtime from generics, is always the least derived form of T, in which case it is always object.
However, if you call new Factory().BuildModel(default(IAddressModel)); , the correct method is being superseded (most likely because it is done at compile time). It seems that dynamic dispatch with generics does not test methods for the derived type itself, even if the method called should be the same, regardless of whether it was executed at compile time or at run time. Ideally, I would like to make the BuildModel (...) methods private and only expose the general method. Is there any other way to get dynamic shift to call the correct method at runtime? I tried changing the implementation of BuildModel<>() to return BuildModel((dynamic)default(T)) , but this raises a run-time error due to the inability to determine which method to send. Is there a way to do this with contravariance and more interfaces?
source share