This is my first Stack Overflow question so pointers on style and content appreciated.
I'm doing some codegen and am making heavy use of dynamic types and unfortunately I've hit the dynamic type/explicit interface conundrum.
I can get around this by using Convert.ChangeType(...)
as outlined here but it requires that IConvertable
is implemented which will have a large overhead that I don't want to have to do.
I've found an example of using Linq expressions to do this using either Expression.TypeAs
or Expression.Convert
, however this always returns the underlying concrete type and not the interface I need.
Here's a code example of what I'm trying to do:
namespace
{
public interface Interface<T> { void Method(T t); }
public class ImplementedInterface : Interface<string> { void Interface<string>.Method(string t) { } }
class Program
{
static void Main(string[] args)
{
var implementedInterface = new ImplementedInterface();
var type = implementedInterface.GetType().GetInterfaces().Single(); // type is an IInterface<string>
dynamic i = Convert(type, implementedInterface); // i is always an ImplementedInterface
i.Method(); // throws exception as method is not found.
}
static object Convert(Type type, object subClass)
{
var body = Expression.TypeAs(Expression.Constant(subClass, subClass.GetType()), type);
var run = Expression.Lambda(body, Expression.Parameter(subClass.GetType())).Compile();
return run.DynamicInvoke(subClass);
}
}
}
Any ideas how I can get what I need with expressions or if there is another option I haven't thought of?
Aucun commentaire:
Enregistrer un commentaire