开发者

C#; making a new delegate without declaring the method separately?

I'm able to compile code that includes this:

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];
            }

but I think my code would look cleaner if I could do something more like this:

OperationDelegate myOpDelegate;
static OperatorDefinition[] definitions ={new OperatorDefinition("+",2,3,true, new OperationDelegate({return args[0]+args[1]}))};
delegate double OperationDelegate(double[] args);

because I want to define everything about each OperatorDefinition in a single place, rather than defining the functions separately. Is there some way to do this in C#?

(any other criticism about my code would be开发者_如何转开发 welcome, too)


Look into anonymous methods... for example this: C# - Anonymous delegate


You can use Lambda expressions as from .Net 3.5:

 static OperatorDefinition[] definitions ={
    new OperatorDefinition("+",2,3,true, 
        args => args[0] + args[1])
    };

In your OperatorDefinition constructor, last parameter should be of type Func<double[],double>

See: http://msdn.microsoft.com/en-us/library/bb397687.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜