Richiamare un metodo usando la riflessione su un oggetto singleton
-
03-07-2019 - |
Domanda
Quindi ho il seguente:
public class Singleton
{
private Singleton(){}
public static readonly Singleton instance = new Singleton();
public string DoSomething(){ ... }
public string DoSomethingElse(){ ... }
}
Usando la riflessione come posso invocare il Metodo DoSomething?
Il motivo per cui lo chiedo è perché memorizzo i nomi dei metodi in XML e creo dinamicamente l'interfaccia utente. Ad esempio, sto creando dinamicamente un pulsante e gli sto dicendo quale metodo chiamare tramite la riflessione quando si fa clic sul pulsante. In alcuni casi sarebbe DoSomething o in altri sarebbe DoSomethingElse.
Soluzione
Non testato, ma dovrebbe funzionare ...
string methodName = "DoSomething"; // e.g. read from XML
MethodInfo method = typeof(Singleton).GetMethod(methodName);
FieldInfo field = typeof(Singleton).GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
method.Invoke(instance, Type.EmptyTypes);
Altri suggerimenti
Ottimo lavoro. Grazie.
Ecco lo stesso approccio con una leggera modifica per i casi in cui non si può avere un riferimento all'assemblaggio remoto. Abbiamo solo bisogno di sapere cose di base come il nome completo della classe (ovvero namespace.classname e il percorso dell'assembly remoto).
static void Main(string[] args)
{
Assembly asm = null;
string assemblyPath = @"C:\works\...\StaticMembers.dll"
string classFullname = "StaticMembers.MySingleton";
string doSomethingMethodName = "DoSomething";
string doSomethingElseMethodName = "DoSomethingElse";
asm = Assembly.LoadFrom(assemblyPath);
if (asm == null)
throw new FileNotFoundException();
Type[] types = asm.GetTypes();
Type theSingletonType = null;
foreach(Type ty in types)
{
if (ty.FullName.Equals(classFullname))
{
theSingletonType = ty;
break;
}
}
if (theSingletonType == null)
{
Console.WriteLine("Type was not found!");
return;
}
MethodInfo doSomethingMethodInfo =
theSingletonType.GetMethod(doSomethingMethodName );
FieldInfo field = theSingletonType.GetField("instance",
BindingFlags.Static | BindingFlags.Public);
object instance = field.GetValue(null);
string msg = (string)doSomethingMethodInfo.Invoke(instance, Type.EmptyTypes);
Console.WriteLine(msg);
MethodInfo somethingElse = theSingletonType.GetMethod(
doSomethingElseMethodName );
msg = (string)doSomethingElse.Invoke(instance, Type.EmptyTypes);
Console.WriteLine(msg);}