Skip to content

Instantly share code, notes, and snippets.

@jnm2
Last active May 20, 2019 14:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jnm2/1c775fe3226cd83ec797 to your computer and use it in GitHub Desktop.
Save jnm2/1c775fe3226cd83ec797 to your computer and use it in GitHub Desktop.
public static class LanguageUtils
{
public static TInterface ExplicitImplementation<TBase, TInterface>(TBase @this)
where TBase : TInterface
where TInterface : class
{
return (TInterface)new ExplicitImplementationProxy(typeof(TBase), @this).GetTransparentProxy();
}
private sealed class ExplicitImplementationProxy : RealProxy, IRemotingTypeInfo
{
private readonly Type baseType;
private readonly object instance;
public ExplicitImplementationProxy(Type baseType, object instance) : base(typeof(MarshalByRefObject))
{
this.baseType = baseType;
this.instance = instance;
}
public bool CanCastTo(Type fromType, object o)
{
return fromType.IsInterface && fromType.IsAssignableFrom(baseType);
}
public string TypeName { get; set; }
public override IMessage Invoke(IMessage msg)
{
var methodCall = msg as IMethodCallMessage;
if (methodCall == null) throw new NotSupportedException();
var map = baseType.GetInterfaceMap(methodCall.MethodBase.DeclaringType);
var args = new object[methodCall.Args.Length];
Array.Copy(methodCall.Args, args, args.Length);
return new ReturnMessage(map.TargetMethods[Array.IndexOf(map.InterfaceMethods, (MethodInfo)methodCall.MethodBase)].Invoke(instance, args), args, args.Length, methodCall.LogicalCallContext, methodCall);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment