听起来像是枚举的工作!
enum YourEnum
{
DoThis,
DoThat
}
YourEnum foo = (YourEnum)yourInt;
Visual Studio 甚至可以使用内置的代码片段创建整个 switch 语句,并且您的代码变得非常可读。
switch(foo)
变成
switch(foo)
{
case YourEnum.DoThis:
break;
case YourEnum.DoThat:
break;
default:
break;
}
更新 1
从可维护性的角度来看,这有点吓人,但是如果您创建了这样的类:
public class ActionProcessor
{
public void Process(int yourInt)
{
var methods = this.GetType().GetMethods();
if (methods.Length > yourInt)
{
methods[yourInt].Invoke(this, null);
}
}
public DoThis()
{
}
public DoThat()
{
}
或者更好但更难维护:
[AttributeUsageAttribute(AttributeTargets.Method,
Inherited = false,
AllowMultiple = false)]
public sealed class AutoActionAttribute : Attribute
{
public AutoActionAttibute(int methodID)
{
this.MethodID = methodID;
}
public int MethodID { get; set; }
}
public class ActionProcessor
{
public void Process(int yourInt)
{
var method = this.GetType().GetMethods()
.Where(x => x.GetCustomAttribute(typeof(AutoActionAttribute),
false) != null
&& x.GetCustomAttribute(typeof(AutoActionAttribute),
false).MethodID == yourInt)
.FirstOrDefault();
if (method != null)
{
method.Invoke(this, null);
}
}
[AutoAction(1)]
public DoThis()
{
}
[AutoAction(2)]
public DoThat()
{
}
}
更新 2(编码我认为 Josh C. 正在谈论的内容)
// Handles all incoming requests.
public class GenericProcessor
{
public delegate void ActionEventHandler(object sender, ActionEventArgs e);
public event ActionEventHandler ActionEvent;
public ProcessAction(int actionValue)
{
if (this.ActionEvent != null)
{
this.ActionEvent(this, new ActionEventArgs(actionValue));
}
}
}
// Definition of values for request
// Extend as needed
public class ActionEventArgs : EventArgs
{
public ActionEventArgs(int actionValue)
{
this.ActionValue = actionValue;
}
public virtual int ActionValue { get; private set; }
}
这将创建负责某些值的 SomeActionProcessor:
// Handles a specific (or multiple) requests
public class SomeActionProcessor
{
public void HandleActionEvent(object sender, ActionEventArgs e)
{
if (e.ActionValue == 1)
{
this.HandleAction();
}
}
private void HandleAction()
{
}
}
然后创建类并将它们连接起来:
GenericProcessor gp = new GenericProcessor();
SomeActionProcessor sap = new SomeActionProcessor();
gp.ActionEvent += sap.HandleActionEvent;
开火并发送通用处理器请求:
gp.ProcessAction(1);