C#/개인공부
람다식 & 문 복습
Bueong_E
2023. 1. 14. 22:53
반응형
SMALL
App Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using static reviewAll01.Earth;
//using static reviewAll01.Earth; // 2022기능으로 알아서 클래스를 가져오더라
namespace reviewAll01
{
class App
{
//람다문 사용전 delegate 선언 (대리자 선언)
delegate int Calculate(int x, int y);
delegate void Test();
delegate string Test2();
public App()
{
//람다문 + 형식 유추 이용
Calculate simplelamda = (a, b) => // 왼쪽은 매개변수 => 오른쪽은 식이 들어간다.
{
int sum = a * b;
if (sum > 100 && sum > a + b)
return 0;
else
{
Console.WriteLine(sum);
return 1;
}
};
//Calculate simplelamda2 = (a, b) => a + b; // 식이 하나만 있을떈 람다식도 사용훈 return 가능.
simplelamda(1, 2);
Console.WriteLine(simplelamda(1, 2));
//람다문 식에는 항상;를 붙여줘야 하더라
Test test = () => {
Console.WriteLine("테스트용 반환값이 없는 람다문 입니다.");
SayHi(); //람다문 안에서 매서드 사용
};
test();
Test2 test2 = () => //string 반환값을 가지는 메서드를 람다문 안에서 사용.
{
Console.WriteLine("test2입니다.");
string name = SayGoodbye("펭귄맨");
Console.WriteLine("{0}님이 떠나셨습니다.", name);
return name;
};
string ttest =test2(); // 반환된 string 을 char 형식으로 변환
Console.WriteLine(ttest);
for(int i =0; i < ttest.Length; i++) // for 문을 이용해 각 string의 인덱스 확인 및 문자 출력
{
Console.WriteLine(ttest[i].GetType());
string tttest = ttest[i].ToString(); //각 요소의 char를 string으로 변환
Console.WriteLine(tttest); //변환된 요소 출력
Console.WriteLine(tttest.GetType()); //변환된 요소 타입 확인
}
}
void SayHi()
{
Console.WriteLine("Hello World!");
}
string SayGoodbye(string name)
{
Console.WriteLine($"{name}님 잘가세요.");
return name;
}
}
}
결과물
좀 중구난방으로 이러면 어떨까 저러면 어떨까 하면서 써봤는데 람다 문에대해 좀더 확신을 가지고 사용할수 있을듯 하다.
람다문과 식또한 작성 방법만 알면 메서드를 보다 편리하게 사용할수 있고 메서드와 거의 동일한 방식으로도 사용 가능하다는걸 알았다. 좀더 응용할수 있는 부분이 많아보여 여러 군데 사용해보며 연구해야겠다.
반응형
LIST