I'm trying to create a simple service selector, to get services from multiple static classes (providers) with methods having the same names. E.g. for a service GetString
:
public static class Provider1 { public static string GetString () { return "1"; } }
public static class Provider2 { public static string GetString () { return "2"; } }
both classes having multiple methods like GetString () to deliver different services. In the application, I need to call GetString
, from a class that is known at runtime. I don't know a better way to select the static type than defining a Type variable, e.g.
Type aType = (condition) ? typeof(Provider1) : typeof(Provider2);
The only refactoring friendly way I know to call the method is to use the string representation of the name:
string _methodName = nameof(Provider1.GetString);
then use reflection to get the method and invoke it.
The whole code:
static void Main () {
Type aType = (new Random ().NextDouble () > .5) ? typeof (Provider1) : typeof (Provider2);
string _methodName = nameof (Provider1.GetString);
MethodInfo aMethod = aType.GetMethod (
_methodName,
BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy);
object result = aMethod.Invoke (null, null);
Console.WriteLine (result.ToString ()); Console.ReadKey ();
}
public static class Provider1 { public static string GetString () { return "1"; } }
public static class Provider2 { public static string GetString () { return "2"; } }
This does works but it's really a ugly piece of code for switching static types at runtime, considering it's only to replace a call like currentProvider.GetString ()
. So I would like to know:
- If there is a better design for switching static class providers.
- If this way is acceptable, can the code be simplified?
Aucun commentaire:
Enregistrer un commentaire