2017-03-10 4 views
0

Ich versuche, eine Liste von Methoden in einer Hash-Tabelle in C# zu speichern, so dass ich in der Lage bin, die Methode vorzufüllen, sobald der Benutzer den erforderlichen Schlüssel eingibt. Ich habe mich gefragt, wie ich das machen würde. Mir wurde gesagt, dass ich sowohl anonyme Schnittstellen als auch Delegierte dafür verwenden kann. Was ist besser und warum? Ich konnte jedoch nicht viel darüber finden, wie dies tatsächlich geschehen würde.Wie speichert man Methoden in einer Hash-Tabelle?

Beispiel:

key = Methode

"+" = object.add

"-" = object.minus

+0

Prüfung [Delegat] (https://msdn.microsoft.com/en-us/library/ms173171.aspx) und [Aktion] (https://msdn.microsoft.com/en-us/ library/018hxwa8 (v = vs.110) .aspx) –

+1

Im Jahr 2017 solltest du keine 'Hashtable' verwenden, du solltest eine' Dictionary ' – xanatos

Antwort

5

Dies ist eine stark vereinfachte Lösung, aber es veranschaulicht die notwendigen Schritte, um Ihre Anforderung zu erfüllen.

public class Test 
{ 
    // Ok, we declare the hashtable here. It could be a Dictionary though, so we don't have to 
    // cast it. But you requested a hashtable. 
    private Hashtable hash = new Hashtable(); 

    // Were it a dictionary, we'd have: 
    // private Dictionary<string, Calculation> dict = new Dictionary<string, Calculation>(); 

    // We declare the signature of the methods that we will store. This means that we accept any 
    // methods which receive two decimal parameters and return a decimal output 
    private delegate decimal Calculation(decimal x, decimal y); 

    public Test() 
    { 
    } 

    public void Run() 
    { 
     // A sample implementation of the delegate 
     Calculation sum = (decimal x, decimal y) => 
     { 
      return x + y; 
     }; 

     // Another sample implementation 
     Calculation minus = (decimal x, decimal y) => 
     { 
      return x - y; 
     }; 

     // Here we add both of them to the hashtable 
     this.hash.Add("+", sum); 
     this.hash.Add("-", minus); 

     // Were it a dictionary, we'd have: 
     // this.dict.Add("+", sum); 
     // this.dict.Add("+", minus); 

     // Note that in the hashtable you can put ANYTHING. Were it a dictionary, it would be strong-typed and 
     // we'd be able to only add Calculation types 

     // Now ask the user for input values 
     Console.Write("X: "); 
     var xInput = decimal.Parse(Console.ReadLine()); 

     Console.Write("Y: "); 
     var yInput = decimal.Parse(Console.ReadLine()); 

     // Ask the user which method to execute 
     Console.WriteLine("Which method to execute? Enter number:"); 
     Console.WriteLine("1. +"); 
     Console.WriteLine("2. -"); 
     Console.Write("> "); 

     var choice = int.Parse(Console.ReadLine()); 

     // Get the selected method from the hashtable 
     Calculation calc; 
     if (choice == 1) 
     { 
      calc = (Calculation)this.hash["+"]; 
     } 
     else if (choice == 2) 
     { 
      calc = (Calculation)this.hash["-"]; 
     } 
     else 
     { 
      throw new ArgumentOutOfRangeException(); 
     } 

     // Were it a dictionary, we'd have (note that we don't have to cast it): 
     // calc = this.dict["-"]; 

     // execute it, and output the result 
     Console.WriteLine("Result: " + calc(xInput, yInput)); 

     Console.ReadKey(); 
    } 
} 
0

In C# zum Speichern der Methodenreferenz gibt es einen Typ namens Delegate. Sie sollten das Wörterbuch der Delegierten verwenden. Zuerst müssen Sie einen Delegaten definieren, der den Signaturen Ihrer Methoden entspricht. Stellen Sie sich vor, Sie haben die Liste der Methoden, die int zurückgibt und zwei int als Parameter akzeptiert. Zuerst definieren Sie Delegat für das.

public delegate int SomeMethodsHandler(int a,int b); 

Und dann erstellen Sie Ihre Methoden.

public int MethodA(int a,int b) 
{ 
     // do some work here 
     return 0; 
} 

public int MethodB(int a,int b) 
{ 
     // do some work here 
     return 1; 
} 

public int MethodC(int a,int b) 
{ 
     // do some work here 
     return 2; 
} 

Und Sie dann Wörterbuch erstellen, die Methoden zu speichern.

Dictionary<string,SomeMethodsHandler> methods = new Dictionary<string,SomeMethodsHandler>(); 

methods["A"] = MethodA; 
methods["B"] = MethodB; 
methods["C"] = MethodC; 

Und wieder, um diese Methoden aufzurufen.

int a = methods["A"](5,7); 
+0

schön .. kannst du bitte sagen ** WIE * * und ** WENN ** diese Art von Aufruf hilfreich ist? –

+0

Frage ist hier, wie Methoden in der Schlüsselwertpaarstruktur gespeichert werden können. Was ist mit deiner Frage ist, dass ich nie über diese Art von Situation komme, wo ich Methodenreferenz im Wörterbuch speichern muss. Delegierte selbst sind jedoch sehr nützlich, wenn Sie Observer-Muster implementieren oder eine Art funktionaler Art ausführen müssen. –

Verwandte Themen