将ObjC块转换为C#Lambdas

时间:2014-06-01 02:39:11

标签: c# objective-c mono xamarin.ios

我需要一些帮助将Objective-C块转换为C#。

这是来源ObjC:

NSDate* addYear = [_calendar dateByAddingComponents:((^{
        NSDateComponents* components = [NSDateComponents new];
        components.month = 12;
        return components;
    })()) toDate:now options:0];

现在我在C#中尝试了以下内容:

NSDate date = _calendar.DateByAddingComponents((() => {
            NSDateComponents components = new NSDateComponents();
            components.Month = 12;
            return components;
        })(), now, NSCalendarOptions.None);

我得到以下编译器错误:Expression denotes a 'anonymous method' where a 'method group' was expected

删除lambda周围的括号会产生Cannot convert 'lambda expression' to non-delegate type 'MonoTouch.Foundation.NSDateComponents'

正确的C#语法是什么?我需要保留闭包,因为我移植的代码库中还有很多东西。

1 个答案:

答案 0 :(得分:4)

这应该有效:

        var date = calendar.DateByAddingComponents (
            new NSDateComponents () 
            {
                Month = 12
            },
            NSDate.Now,
            NSCalendarOptions.None);

编辑:你可能需要一个Func:

        Func<NSDateComponents> func = () => new NSDateComponents () { Month = 12 };

        date = calendar.DateByAddingComponents (func (), NSDate.Now, NSCalendarOptions.None);

在方法中:

        date = calendar.DateByAddingComponents (
            (new Func<NSDateComponents>(()=> new NSDateComponents () { Month = 12 }))(),
            NSDate.Now,
            NSCalendarOptions.None);