c# 기초구문 업데이트 완료

This commit is contained in:
2025-03-05 11:57:12 +09:00
parent 15885a2286
commit 6ebd0fb5a9
22 changed files with 740 additions and 0 deletions
+10
View File
@@ -0,0 +1,10 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net8.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
</Project>
+131
View File
@@ -0,0 +1,131 @@
internal class Program
{
private static void Main(string[] args)
{
Console.WriteLine("Hello, World!");
}
}
class AClass
{
public void Run()
{
// Action<T>
// 입력 : T 타입
// 리턴갑 : 없음
// 기존 메서드 지정
System.Action<string> act = Output;
act("Hello");
// 무명 메서드 지정
Action<string, string> act2 = delegate (string msg, string title)
{
Console.WriteLine(msg, title);
};
act2("No data found", "Error");
// 람다식 사용
Action<int> act3 = code => Console.WriteLine("Code: {0}", code);
act3(1033);
}
void Output(string s)
{
Console.WriteLine(s);
}
}
class BClass
{
int _state;
//---------------------
// 예제 1
// Func<TResult>
// 입력: 없음
// 리턴: TResult 타입
//---------------------
public void Run()
{
// 메서드 지정
System.Func<bool> f = IsValid;
bool result = f();
// 무명 메서드 지정
Func<bool> fa = delegate
{
return _state == 0;
};
result = fa();
// 람다식 이용
Func<bool> fb = () => _state == 0;
result = fb();
}
bool IsValid()
{
return _state == 0;
}
//---------------------
// 예제 2
// Func<T1, TResult>
// 입력: 1개
// 리턴: TResult 타입
//---------------------
public void Run1()
{
// 메서드 지정
System.Func<int, bool> f = IsValidRange;
bool result = f(10);
// 무명 메서드 지정
Func<int, bool> fa = delegate (int n)
{
return n > 0;
};
result = fa(-1);
// 람다식 이용
Func<int, bool> fb = n => n > 0;
result = fb(-2);
}
bool IsValidRange(int n)
{
return n > 0;
}
void Predicate()
{
// Predicate<T>
Predicate<int> p = delegate (int n)
{
return n >= 0;
};
bool res = p(-1);
Predicate<string> p2 = s => s.StartsWith("A");
res = p2("Apple");
}
public void UsePredicate()
{
int[] arr = { -10, 20, -30, 4, -5 };
// Predicate의 사용
// Array.Find(int[], Predicate<int>)
int pos = Array.Find(arr, IsPositive);
// LINQ에서 Func의 사용
// Where(Func<int, bool> predicate)
var v = arr.Where(n => n >= 0);
}
bool IsPositive(int i)
{
return i >= 0;
}
}