C#;在不单独声明方法的情况下创建新委托?

C#;在不单独声明方法的情况下创建新委托?,c#,syntax,delegates,C#,Syntax,Delegates,我能够编译包含以下内容的代码: OperationDelegate myOpDelegate; static OperatorDefinition[] definitions ={ new OperatorDefinition("+",2,3,true, new OperationDelegate(OperationAdd)), }; delegate double OperationDelegate(double[] args); sta

我能够编译包含以下内容的代码:

OperationDelegate myOpDelegate;
static OperatorDefinition[] definitions ={
                new OperatorDefinition("+",2,3,true, new OperationDelegate(OperationAdd)),
            };
delegate double OperationDelegate(double[] args);
static double OperationAdd(double[] args)
            {
                return args[0] + args[1];
            }
但我认为如果我能做更多类似的事情,我的代码会看起来更干净:

OperationDelegate myOpDelegate;
static OperatorDefinition[] definitions ={new OperatorDefinition("+",2,3,true, new OperationDelegate({return args[0]+args[1]}))};
delegate double OperationDelegate(double[] args);
因为我想在一个地方定义每个运算符的所有定义,而不是单独定义函数。在C#中有什么方法可以做到这一点吗


(对我的代码的任何其他批评都是欢迎的)

研究匿名方法。。。例如:

您可以使用.Net 3.5中的Lambda表达式:

 static OperatorDefinition[] definitions ={
    new OperatorDefinition("+",2,3,true, 
        args => args[0] + args[1])
    };
运算符定义
构造函数中,最后一个参数的类型应为
Func

见:

谢谢;只要知道“匿名委托”这个词,我就能很快找到很多例子。“我不知道我不知道什么”~I
have
。很高兴您找到了所需的@dividerI,结果是“new OperatorDefinition(“*”,2,4,true,delegate(double[]args){return args[0]*args[1];}”;这比你的更糟吗?这是一个品味问题-我认为Lambda更短,更容易阅读谢谢你的帮助,但是指向MSDN的链接被截断了。试试Lambda表达式吧……它们整洁、干净、简洁。