[c#] 익명 메서드로 값을 반환하는 방법은 무엇입니까?

이것은 실패합니다

string temp = () => {return "test";};

오류와 함께

람다식이 대리자 형식이 아니기 때문에 ‘문자열’형식으로 변환 할 수 없습니다.

오류의 의미는 무엇이며 어떻게 해결할 수 있습니까?



답변

여기서 문제는 a를 반환하는 익명 메서드를 정의 string했지만 string. 호출 될 때 string직접 생성 되지 않는 표현식입니다 string. 호환되는 대리자 유형에 할당해야합니다. 이 경우 가장 쉬운 선택은Func<string>

Func<string> temp = () => {return "test";};

이 작업은 약간의 캐스팅을 통해 한 줄로 수행하거나 대리자 생성자를 사용하여 람다 형식을 설정 한 다음 호출을 수행 할 수 있습니다.

string temp = ((Func<string>)(() => { return "test"; }))();
string temp = new Func<string>(() => { return "test"; })();

참고 : 두 샘플 모두 부족한 표현 형식으로 단락 될 수 있습니다. { return ... }

Func<string> temp = () => "test";
string temp = ((Func<string>)(() => "test"))();
string temp = new Func<string>(() => "test")();


답변

문자열 유형에 함수 대리자 를 할당하려고 합니다. 이 시도:

Func<string> temp = () => {return "test";};

이제 다음과 같이 함수를 실행할 수 있습니다.

string s = temp();

“s”변수는 이제 “test”값을 갖습니다.


답변

약간의 도우미 함수와 제네릭을 사용하면 컴파일러가 유형을 추론하고 약간 단축 할 수 있습니다.

public static TOut FuncInvoke<TOut>(Func<TOut> func)
{
    return func();
}

var temp = FuncInvoke(()=>"test");

참고 : 이것은 익명 유형을 반환 할 수 있기 때문에 좋습니다.

var temp = FuncInvoke(()=>new {foo=1,bar=2});


답변

인수와 함께 익명 메서드를 사용할 수 있습니다.

int arg = 5;

string temp = ((Func<int, string>)((a) => { return a == 5 ? "correct" : "not correct"; }))(arg);


답변

익명 메서드는 func 대리자를 사용하여 값을 반환 할 수 있습니다. 다음은 익명 메서드를 사용하여 값을 반환하는 방법을 보여주는 예입니다.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {


        static void Main(string[] args)
        {
            Func<int, int> del = delegate (int x)
              {
                  return x * x;

              };

            int p= del(4);
            Console.WriteLine(p);
            Console.ReadLine();
        }
    }
}


답변

이것은 C # 8을 사용하는 또 다른 예입니다 ( 병렬 작업을 지원하는 다른 .NET 버전에서도 작동 할 수 있음 ).

using System;
using System.Threading.Tasks;

namespace Exercise_1_Creating_and_Sharing_Tasks
{
    internal static class Program
    {
        private static int TextLength(object o)
        {
            Console.WriteLine($"Task with id {Task.CurrentId} processing object {o}");
            return o.ToString().Length;
        }

        private static void Main()
        {
            const string text1 = "Welcome";
            const string text2 = "Hello";

            var task1 = new Task<int>(() => TextLength(text1));
            task1.Start();

            var task2 = Task.Factory.StartNew(TextLength, text2);

            Console.WriteLine($"Length of '{text1}' is {task1.Result}");
            Console.WriteLine($"Length of '{text2}' is {task2.Result}");

            Console.WriteLine("Main program done");
            Console.ReadKey();
        }
    }
}


답변