【发布时间】:2014-08-15 08:28:03
【问题描述】:
首先,我很抱歉,因为我的问题很愚蠢。但我希望有人能在这种方法上帮助我。
我有一个枚举,我想按照描述添加新的魔法属性:
public enum FunctionType
{
[CallMethod(ExecuteFunction.DOPLUS)] //How to implement CallMethod magic attribute
PLUS,
[CallMethod(ExecuteFunction.DOMINUS)]
MINUS,
[CallMethod(ExecuteFunction.DOMULTIPLY)]
MULTIPLY,
[CallMethod(ExecuteFunction.DODIVIDE)]
DIVIDE
}
我的班级有这样的 FunctionType 属性:
public class Function
{
private FunctionType _functionType;
public List<object> Params
{ get; set; }
public FunctionType FunctionType
{
get { return _functionType; }
set { _functionType = value; }
}
public string Execute()
{
return SomeMagicMethod(this.FunctionType); //How to implement this method to return my result as expected
}
}
最后,我的计算类有一些函数返回结果:
public static class ExecuteFunction
{
public static string DOPLUS(int a, int b)
{
return (a + b).ToString();
}
public static string DOMINUS(int a, int b)
{
return (a - b).ToString();
}
public static string DOMULTIPLY(int a, int b)
{
return (a * b).ToString();
}
public static string DODIVIDE(int a, int b)
{
return (a / b).ToString();
}
}
我的愚蠢问题是:如何在上面的枚举和 SomeMagicMethod 中实现 CallMethodAttribute 以运行指定的方法而不像往常一样使用 switch case?
【问题讨论】:
-
暂时忘记 calling 部分 - 您的属性现在根本无法编译,因为该属性的参数必须是编译时常量几个受支持类型之一的值。不过,您可以有一个 string 来指定方法的名称。顺便说一句,我强烈建议遵循 .NET 命名约定 - 去掉那些喧闹的名字。
标签: c# reflection enums