Bir lambda işlevi bildirmek ve hemen çağırmak mümkündür:
Func<int, int> lambda = (input) => { return 1; };
int output = lambda(0);
Bir satırda bunu yapmanın mümkün olup olmadığını merak ediyorum, örneğin
int output = (input) => { return 1; }(0);
derleyici hatası "Yöntem adı bekleniyor" verir. İçin yayınlama da Func<int, int>çalışmıyor:
int output = (Func<int, int>)((input) => { return 1; })(0);
aynı hatayı verir ve aşağıda belirtilen nedenlerden ötürü, giriş bağımsız değişken türünü (ilk int) açıkça belirtmek istemiyorum .
Muhtemelen sadece kodu doğrudan gömmek yerine neden bunu yapmak istediğimi merak ediyorsunuz , örneğin int output = 1;. Nedeni aşağıdaki gibidir: svcutilİç içe geçmiş öğeler nedeniyle yazmak zorunda kalmamak için son derece uzun sınıf adları üreten bir SOAP web hizmeti için bir başvuru oluşturdum. Yani yerine
var o = await client.GetOrderAsync(request);
return new Order {
OrderDate = o.OrderDate,
...
Shipments = o.Shipment_Order == null ? new Shipment[0]
o.Shipment_Order.Select(sh => new Shipment {
ShipmentID = sh.ShipmentID,
...
Address = CreateAddress(sh.ReceiverAddress_Shipment);
}).ToArray()
};
ve ayrı bir CreateAddress(GetOrderResultOrderShipment_OrderShipmentShipment_Address address)yöntem (gerçek isimler daha da uzun ve form üzerinde çok sınırlı kontrole sahibim) yazmak istiyorum
var o = await client.GetOrderAsync(request);
return new Order {
OrderDate = o.OrderDate,
...
Shipments = o.Shipment_Order == null ? new Shipment[0]
o.Shipment_Order.Select(sh => new Shipment {
ShipmentID = sh.ShipmentID,
...
Address = sh.ReceiverAddress_Shipment == null ? null : () => {
var a = sh.ReceiverAddress_Shipment.Address;
return new Address {
Street = a.Street
...
};
}()
}).ToArray()
};
Yazabileceğimi biliyorum
Address = sh.ReceiverAddress_Shipment == null ? null : new Address {
Street = sh.ReceiverAddress_Shipment.Address.Street,
...
}
ancak bu ( sh.ReceiverAddress_Shipment.Addressbölüm) bile çok alan varsa çok tekrarlanır hale gelir. Bir lambda ilan etmek ve hemen çağırmak, daha az karakter yazmak için daha zarif olurdu .
public T Exec<T>(Func<T> func) => return func();ve bunu şöyle kullanın: int x = Exec(() => { return 1; });Bana göre tüm parensleri ile dökümden çok daha güzel okuyor.
int output = ((Func<int>) (() => { return 1; }))();