본문 바로가기

C#/C# Common19

Dictionary를 다른 Dictionary에 복사하는 방법 1. Constructor를 사용한 복사Dictionary originalDict = new Dictionary(){ { "One", 1 }, { "Two", 2 }, { "Three", 3 }};Dictionary copiedDict = new Dictionary(originalDict); 2. ToDictionary() 메소드를 사용한 복사using System.Linq;Dictionary originalDict = new Dictionary(){ { "One", 1 }, { "Two", 2 }, { "Three", 3 }};Dictionary copiedDict = originalDict.ToDictionary(entry => entry.Key, entry => en.. 2024. 9. 29.
File File Sizeif (!File.Exists(filePath)){ return;}FileInfo info = new FileInfo(filePath);long fileSize = info.Length; 2024. 6. 10.
Attribute 메타데이터를 코드에 추가하는 데 사용되는 구조체 1. Obsolete : 클래스나 메서드가 더 이상 사용되지 않고 대체될 것임을 표시class Program{ // ObsoleteMethod => Warning [Obsolete("삭제 예정. ModifiedMethod() 추천")] public static void ObsoleteMethod() { Console.WriteLine("삭제 예정 함수(경고)"); } // ObsoleteMethod => Error [Obsolete("삭제 예정. ModifiedMethod() 사용 필수", true)] public static void ObsoleteMethod() { Console.WriteLine("삭제 예.. 2024. 5. 11.
Upcasting using System; namespace Upcasting { internal class Program { static void Main(string[] args) { Child c = new Child(); Console.WriteLine($"[ Before Upcasting ]"); Console.WriteLine($"{c.GetType()}"); Console.WriteLine($"{c.Name}"); c.Do1(); c.Do2(); Console.WriteLine($""); Parent p = (Parent)c; Console.WriteLine($"[ After Upcasting ]"); Console.WriteLine($"{p.GetType()}"); Console.WriteLine($"{p... 2023. 5. 18.
키보드 보조키 상태 확인 Shift, Alt, Ctrl Keys key; /// Shift key = Keys.Shift; if ((Control.ModifierKeys & key) == key) { Console.WriteLine("Shift key pressed"); } /// Shift key = Keys.Alt; if ((Control.ModifierKeys & key) == key) { Console.WriteLine("Alt key pressed"); } /// Ctrl key = Keys.Control; if ((Control.ModifierKeys & key) == key) { Console.WriteLine("Ctrl key pressed"); } 2023. 1. 30.
Tuple (함수 반환값 여러개 사용하기) 여러개 반환값을 사용하는 함수 public Tuple ShowInputInteger(string title, int min, int max, int value) { bool retFlag; int retValue; if (true) { retFlag = true; retValue = 1; } else { retFlag = false; retValue = 0; } return (new Tuple(ret, dlgValue)); } 여러개 반환값을 받아 사용 var ret = ShowInputInteger("Test", 0, 9999, 30); if (ret.Item1) { MessageBox.Show($"return value is {ret.Item2}"); } 2022. 10. 9.
string - byte array using System; using System.IO; using System.Text; namespace String_Byte { class Program { static void DisplayBytes(byte[] bytes, bool nextLine = true) { foreach (byte b in bytes) { Console.Write($"{b:X2} "); } if (nextLine) { Console.WriteLine(); } } static void EncodingDefault() { string caseString = "Case 1 - Encoding.Default"; byte[] bytes = Encoding.Default.GetBytes(caseString); Console.Writ.. 2022. 9. 9.
프로세스 찾기 using System; using System.Diagnostics; using System.IO; namespace ProcessFinder { class Program { static void Main(string[] args) { string processName = Path.GetFileNameWithoutExtension(System.AppDomain.CurrentDomain.FriendlyName); IntPtr handle = SearchHandle(processName); Console.WriteLine($"{processName} handle is {handle}"); Console.ReadKey(); } static IntPtr SearchHandle(string targetName).. 2022. 9. 9.
스크린 정보 using System; using System.Windows.Forms; namespace ScreenInformation { internal class Program { static void Main(string[] args) { Screen[] s = Screen.AllScreens; for (int i = 0; i < s.Length; i++) { Console.WriteLine($"[{i + 1}]"); Console.WriteLine($"Primary : {s[i].Primary}"); Console.WriteLine($"DeviceName : {s[i].DeviceName}"); Console.WriteLine($"BitsPerPixel : {s[i].BitsPerPixel}"); Conso.. 2022. 9. 9.
Reflection Reflection 어셈블리, 모듈 및 형식을 설명하는 개체(Type) 제공 동적으로 형식 인스턴스를 생성 기존 개체에서 형식을 가져와 해당 메서드 호출, 필드 및 속성 액세스 코드에서 특성을 사용하는 경우 특성에 대한 액세스 제공 using System; using System.Reflection; namespace Reflection { class Program { static void Main(string[] args) { var assembly = Assembly.GetExecutingAssembly(); Console.WriteLine(assembly.FullName); Console.WriteLine(); var types = assembly.GetTypes(); foreach (var typ.. 2022. 9. 6.
Generics Generics 형식 인수를 생략하고 컴파일러에서 자동으로 유추하도록 한다. using System; namespace Generics { class Program { static void Main(string[] args) { var r1 = new Result { Success = true, Data = 5, Data2 = "Hello" }; var r2 = new Result { Success = true, Data = "John", Data2 = true }; Console.WriteLine(r1.ToString()); Console.WriteLine(r2.ToString()); Console.WriteLine(); var helper = new ResultPrinter(); helper.Prin.. 2022. 9. 4.
?. ??= ?. ??= Visual Studio 2022 .Net 6.0 Console Application Person? p1 = null; Person? p2 = new Person("John", 23); Console.WriteLine(p1?.Name); Console.WriteLine(p2?.Name); Console.WriteLine($"p1 is {(p1 ?? new Person("Bob", 12)).ToString()}"); List pl = new List(); (pl ??= new List()).Add(new Person("Jane", 23)); Console.WriteLine($"{pl.Count} : {pl[0].ToString()}"); (pl ??= new List()).Add(new Per.. 2022. 9. 4.
Extension Methods Extension Methods 기능 기존 클래스의 인스턴스 메서드처럼 사용 기존 클래스의 내용을 변경하지 않고 기능 확장 구성 static class 안에 static method 형태로 구성 된다. 메서드의 첫번째 파라메터는 확장하려는 클래스로 고정된다. 첫번째 파라메터 클래스명 앞에 this 를 붙여준다 using System; namespace ExtensionMethods { class Program { static void Main(string[] args) { var p = new Person { Name = "John", Age = 33 }; var p2 = new Person { Name = "Sally", Age = 35 }; p.SayHello(p2); Console.ReadKey().. 2022. 9. 3.
LINQ LINQ Case 1 using System; using System.Linq; namespace LinqSample { class Program { static void Main(string[] args) { var sample = "I enjoy writing uber-software in C#"; var result = from c in sample select c; foreach (var item in result) { Console.Write(item); } Console.WriteLine(); Console.ReadKey(); } } } Case 2 - where, orderby using System; using System.Linq; namespace LinqSample { class Pr.. 2022. 9. 1.
Event Event using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Event { class Program { static void Main(string[] args) { var tower = new ClockTower(); var john = new Person("John", tower); tower.ChimeFivePM(); tower.ChimeSixAM(); Console.ReadKey(); } } public class Person { private string _name; private ClockTower _tower; publi.. 2022. 8. 30.
Anonymous Methods and Lambda Expression Anonymous Methods and Lambda Expression 아래 기술된 코드는 실행 결과가 모두 같다. 익명 함수에서 람다식으로 변형되는 과정이다. 방식 1 using System; namespace AnonymousMethodAndLambda { internal class Program { delegate void Operation(int num); static void Main(string[] args) { Operation op = Double; op(2); Console.ReadKey(); } static void Double(int num) { Console.WriteLine("{0} x 2 = {1}", num, num * 2); } } } 방식 2 using System; nam.. 2022. 8. 30.
Generic https://www.youtube.com/watch?v=l6s7AvZx5j8 2022. 8. 16.
가변 인수 가변 인수 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Params { internal class Program { static void Main(string[] args) { params_int(1, 2, 3, 4, 5); params_object(1, 'a', "Hello", "World"); int[] ints = { 1, 2, 3, 4, 5 }; params_int(ints); object[] objs = { 1, 'a', "one", "two", 10 }; params_object(objs); Console.ReadL.. 2022. 6. 30.
Async & Sync 비동기 프로그래밍 Async & Sync 비동기 프로그래밍 using System; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace AsyncAwait { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { // case 1 //label1.Text = BigLongImportantMethod("John"); // case 2 : Task //Task.Factory.StartNew(() => BigLongImportant.. 2022. 6. 22.