vendredi 17 juillet 2015

Is there a typed way to declare a method name in C#

I have some reflection code and I would love to have a way of binding the method names to types instead of declaring through strings.

I have this interface:

interface IDoStuff<T> {
    void Do(T stuff);
}

Then I have this code:

object stuff = GotThisFromSomewhereElse();
object doer = GotThisFromSomewhereElseAlso();
var doMethodInfo = doer.GetType().GetMethod("Do");
doMethodInfo.Invoke(doer, new[] { stuff });

The problem is that I can't simply do a safe cast and call it because it's generic and I don't actually know what type T is.

This works fine but when I rename the method I have to go update this, I'm not overly concerned as I have tests to confirm all of this works which protects against not knowing it changed.

It's just really ugly and I was curious if there is some slick way to have this typed and thus will get renamed by ReSharper if I change it.

I'd really like something like:

object stuff = GotThisFromSomewhereElse();
object doer = GotThisFromSomewhereElseAlso();
var doMethodInfo = doer.GetType().Methods.Do;
doMethodInfo.Invoke(doer, new[] { stuff });

Thanks in advance and please let me know if this is something that is possible in C#.





Aucun commentaire:

Enregistrer un commentaire