Skip to content

Instantly share code, notes, and snippets.

@MarcusVoelker
Last active August 29, 2015 14:17
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 MarcusVoelker/a0eb64ef03e87be23b6b to your computer and use it in GitHub Desktop.
Save MarcusVoelker/a0eb64ef03e87be23b6b to your computer and use it in GitHub Desktop.
InstanceHelper
public class GenericInstanceHelper<TBase,TI1>
{
public TBase Instance { get; private set; }
public TI1 Interface { get; private set; }
private GenericInstanceHelper() {}
public static GenericInstanceHelper<TBase, TI1> Create<T>(T instance)
where T : TBase, TI1
{
return new GenericInstanceHelper<TBase, TI1> {Instance = instance, Interface = instance};
}
public void Set<T>(T instance)
where T : TBase, TI1
{
Instance = instance;
Interface = instance;
}
public static implicit operator TBase(GenericInstanceHelper<TBase, TI1> instance)
{
return instance.Instance;
}
public delegate object Callinator(params object[] objs);
public Callinator this[string name]
{
get
{
return objs =>
{
var method = typeof (TBase).GetMethod(name, objs.Select(o => o.GetType()).ToArray());
if (method != null)
return method.Invoke(Instance, objs);
method = typeof(TI1).GetMethod(name, objs.Select(o => o.GetType()).ToArray());
if (method != null)
return method.Invoke(Instance, objs);
throw new ArgumentException("Could not find method " + name);
};
}
}
}
internal interface I
{
int Foo(int i);
}
internal class B
{
public int TestFunc(int i)
{
return 1;
}
public int TestFunc(float i)
{
return 2;
}
}
class Test : B,I
{
public int Foo(int i)
{
return 3;
}
public static void Main(string[] args)
{
var ih = GenericInstanceHelper<B, I>.Create(new Test());
Console.WriteLine(ih["TestFunc"](1));
Console.WriteLine(ih["TestFunc"](1.0f));
Console.WriteLine(ih["Foo"](1));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment