Is it possible to declare and use an anonymous function in one expression?

Is there a way to combine the following two lines into one statement?

Func<XmlNode> myFunc = () => { return myNode; };
XmlNode myOtherNode = myFunc();

I tried things like below, but I can’t make it work and I can’t determine from the documentation whether this should work or not?

XmlNode myOtherNode = ((Func<XmlNode>) () => { return myNode; })();
+3
source share
4 answers

I'm not sure why you want to do this, but ..

XmlNode myOtherNode = new Func<XmlNode>( () => { return myNode; } )();

gotta do the trick.

+6
source

The “trick” is that you need to create a delegate instance for it to work, which in your example is the implicit execution of the job (myFunc = ...). Alternatively, you can express your function as () => myNode to make it shorter.

XmlNode myOtherOne = new Func<XmlNode>( () => myNode )();
+2
source

, "headling", .

, lambda (=>), delegate:

XmlNode myOtherNode = ((Func<XmlNode>) delegate { return myNode; })();

, : ? ...

XmlNode myOtherNode = myNode;
+2

, :

namespace FunWithContractsAndAnonymousDelegates
{
    using System;
    using System.Collections.Generic;
    using System.Diagnostics.Contracts;
    using System.Linq;

    internal static class Program
    {
        private static void MySort<T>(T[] array, int index, int length, IComparer<T> comparer)
        {
            Contract.Requires<ArgumentNullException>(array != null);
            Contract.Requires<ArgumentOutOfRangeException>(index >= 0 && index <= array.Length);
            Contract.Requires<ArgumentOutOfRangeException>(length >= 0 && index + length <= array.Length);
            Contract.Ensures(new Func<T[], int, int, IComparer<T>, bool>((_array, _index, _length, _comparer) =>
                {
                    T[] temp = (T[])_array.Clone();
                    Array.Sort(temp, _index, _length, _comparer);
                    return temp.SequenceEqual(_array);
                })(array, index, length, comparer));

            // TODO: Replace with my heavily optimized and parallelized sort implementation...
            Array.Sort(array, index, length, comparer);
        }

        private static void Main(string[] args)
        {
            int[] array = { 3, 2, 6, 1, 5, 0, 4, 7, 9, 8 };
            MySort(array, 0, array.Length, Comparer<int>.Default);
            foreach (int value in array)
            {
                Console.WriteLine(value);
            }
        }
    }
}

, , (.. Contract.Ensures).

, , ...

0

Source: https://habr.com/ru/post/1705499/


All Articles