Last active
August 29, 2015 14:17
-
-
Save MarcusVoelker/a0eb64ef03e87be23b6b to your computer and use it in GitHub Desktop.
InstanceHelper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
}; | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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