Question

J'ai donc les éléments suivants:

public class Singleton
{

  private Singleton(){}

  public static readonly Singleton instance = new Singleton();

  public string DoSomething(){ ... }

  public string DoSomethingElse(){ ... }

}

Utilisation de la réflexion, comment puis-je invoquer la méthode DoSomething?

La raison que je pose est que je stocke les noms de méthodes en XML et crée dynamiquement l'interface utilisateur. Par exemple, je crée de manière dynamique un bouton et lui indique quelle méthode appeler via une réflexion lorsque le bouton est cliqué. Dans certains cas, ce serait Do Quelque chose ou dans d'autres, ce serait Do SomethingElse.

Était-ce utile?

La solution

Non testé, mais devrait fonctionner ...

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);

Autres conseils

Excellent travail. Merci.

Voici la même approche avec une légère modification pour les cas où il est impossible de faire référence à l’assemblage distant. Nous avons juste besoin de connaître des éléments de base tels que la classe nom complet (par exemple, namespace.classname et le chemin d'accès à l'assembly distant).

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);}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top