मुझे एहसास है कि यह एक पुरानी पोस्ट है, लेकिन इन स्थितियों में मुझे विशेषताओं और कारखाने को बहुत आसान लगता है।
निम्न कोड आपको एक कस्टम विशेषता (Command
) का उपयोग करता है ताकि आप अपनी विधियों को विशेषता दे सकें, जिससे आपको यह पता चल सके कि उन्हें आपको कैसे जवाब देना चाहिए।
कारखाने विधि प्रतिबिंब का उपयोग करता है इन तरीकों में से एक शब्दकोश उत्पन्न करने के लिए है और यह कहता है कि जब भी आप CommandFactory
कहते हैं।
हालात थोड़ा साफ कर सकता हो, आह्वान बुला एक छोटे बदसूरत है, लेकिन यह सिर्फ तुम कैसे कोड निष्पादित करने के लिए चाहते हैं पर निर्भर करता है।
using System.Collections.Generic;
using System.Linq;
namespace MyApp
{
using System.Reflection;
using MyApp.Commands;
class Program
{
static void Main(string[] args)
{
var methods = new MyCommands();
MethodInfo myMethod;
myMethod = CommandFactory.GetCommandMethod("Show Commands");
myMethod.Invoke(methods, null);
myMethod = CommandFactory.GetCommandMethod("Close window");
myMethod.Invoke(methods, null);
myMethod = CommandFactory.GetCommandMethod("Switch window");
myMethod.Invoke(methods, null);
}
}
public static class CommandFactory
{
private static Dictionary<string, MethodInfo> speechMethods = new Dictionary<string, MethodInfo>();
public static MethodInfo GetCommandMethod(string commandText)
{
MethodInfo methodInfo;
var commands = new MyCommands();
if (speechMethods.Count == 0)
{
var methodNames =
typeof(MyCommands).GetMethods(BindingFlags.Public | BindingFlags.DeclaredOnly | BindingFlags.Instance);
var speechAttributeMethods = methodNames.Where(y => y.GetCustomAttributes().OfType<CommandAttribute>().Any());
foreach (var speechAttributeMethod in speechAttributeMethods)
{
foreach (var attribute in speechAttributeMethod.GetCustomAttributes(true))
{
speechMethods.Add(((CommandAttribute)attribute).Command, speechAttributeMethod);
}
}
methodInfo = speechMethods[commandText];
}
else
{
methodInfo = speechMethods[commandText];
}
return methodInfo;
}
}
}
namespace MyApp.Commands
{
class MyCommands
{
[Command("Show All")]
[Command("Show All Commands")]
[Command("Show commands")]
public void ShowAll()
{
ProgramCommands.ShowAllCommands();
}
[Command("Close Window")]
public void CloseWindow()
{
ControlCommands.CloseWindow();
}
[Command("Switch Window")]
public void SwitchWindow()
{
ControlCommands.SwitchWindow();
}
}
[System.AttributeUsage(System.AttributeTargets.Method, AllowMultiple = true)]
public class CommandAttribute : System.Attribute
{
public string Command
{
get;
set;
}
public CommandAttribute(string textValue)
{
this.Command = textValue;
}
}
}
समान हस्ताक्षर वाले सभी कार्य हैं? – elyashiv
यह http://codereview.stackexchange.com/ के लिए बेहतर अनुकूल हो सकता है। –
जब भी आप स्वयं को कोड लिखते हैं जो एक विधि का प्रतिनिधित्व करने के लिए * स्ट्रिंग * का उपयोग करता है तो आपको सबसे पहले "प्रतिनिधि" को सोचना चाहिए। –