전체 글1130 InterlockedIncrement로 안전한 정수 증가 처리하기 InterlockedIncrement로 안전한 정수 증가 처리하기 멀티스레드 환경에서 동일한 변수를 동시에 증가시키면 경합 조건(Race Condition)이 발생할 수 있습니다. 델파이의 InterlockedIncrement 함수는 원자적(Atomic)으로 정수 값을 증가시켜 스레드 충돌을 방지합니다. uses System.SyncObjs, System.Classes, System.SysUtils; var Counter: Integer = 0; procedure IncrementInThread; begin TThread.CreateAnonymousThread(procedure var I: Integer; begin for I := 1 to 1000 do .. 2025. 5. 7. Stopwatch로 코드 실행 시간 측정하기 Stopwatch로 코드 실행 시간 측정하기 성능을 측정하거나 특정 블록의 실행 시간을 확인하고 싶을 때, System.Diagnostics.Stopwatch 클래스를 사용하면 정확한 시간 측정이 가능합니다. using System; using System.Diagnostics; using System.Threading; class Program { static void Main() { Stopwatch sw = new Stopwatch(); sw.Start(); Thread.Sleep(1500); // 테스트용으로 1.5초 대기 sw.Stop(); Console.WriteLine($"실행 시간: {sw.Elapse.. 2025. 5. 7. for..in 반복문을 사용한 컬렉션 순회 for..in 반복문을 사용한 컬렉션 순회 델파이의 for..in 구문은 배열이나 리스트, 문자열, 컬렉션 등을 간단하게 순회할 수 있게 해주는 문법입니다. 기존의 인덱스 기반 반복문보다 가독성이 좋고, 실수 가능성이 적어 더욱 안전합니다. uses System.SysUtils, System.Classes; procedure ForInExample; var List: TStringList; S: string; begin List := TStringList.Create; try List.Add('Delphi'); List.Add('개발'); List.Add('재미있어요'); for S in List do ShowMessage(S); fina.. 2025. 5. 5. string.Contains()로 문자열 포함 여부 간단히 확인하기 string.Contains()로 문자열 포함 여부 간단히 확인하기 C#의 string.Contains() 메서드를 사용하면 텍스트 내에 특정 문자열이 포함되어 있는지를 간단하고 직관적으로 검사할 수 있습니다. 검색, 필터링, 조건 분기 등에 유용하게 사용됩니다. using System; class Program { static void Main() { string message = "안녕하세요, 모노솔루션입니다."; if (message.Contains("모노")) { Console.WriteLine("✅ 회사명이 포함되어 있습니다."); } else { .. 2025. 5. 5. FreeAndNil을 사용한 메모리 해제와 포인터 초기화 FreeAndNil을 사용한 메모리 해제와 포인터 초기화 델파이에서 객체를 메모리에서 해제한 뒤 포인터를 nil로 초기화하지 않으면, 이후 해당 포인터를 접근하려 할 때 오류(Access Violation)가 발생할 수 있습니다. FreeAndNil은 이 두 과정을 한 번에 처리해주는 안전한 도구입니다. uses System.SysUtils; procedure FreeAndNilExample; var Obj: TStringList; begin Obj := TStringList.Create; try Obj.Add('Delphi is powerful!'); finally FreeAndNil(Obj); // 메모리 해제 + 포인터 nil 처리 end; if Obj .. 2025. 5. 1. List<T>.Find()로 조건에 맞는 첫 번째 항목 찾기 List.Find()로 조건에 맞는 첫 번째 항목 찾기 List의 Find() 메서드는 조건을 만족하는 첫 번째 요소를 간편하게 찾을 수 있는 기능입니다. 복잡한 반복문 없이도 원하는 항목을 빠르게 추출할 수 있어 실용적입니다. using System; using System.Collections.Generic; class Program { static void Main() { List names = new List { "John", "Jane", "Steve", "Sara" }; string result = names.Find(name => name.StartsWith("S")); Console.WriteLine("조건에 맞는 이름: " +.. 2025. 5. 1. Pos 함수를 활용한 문자열 내 위치 검색 Pos 함수를 활용한 문자열 내 위치 검색 델파이의 Pos 함수는 특정 문자열이 다른 문자열 내 어디에 위치하는지를 알려주는 함수입니다. 검색 기능, 유효성 검사, 문자열 파싱 등 다양한 곳에서 활용할 수 있습니다. uses System.SysUtils; procedure PosExample; var Text, SubStr: string; Index: Integer; begin Text := 'Welcome to the Delphi world!'; SubStr := 'Delphi'; Index := Pos(SubStr, Text); ShowMessage('위치: ' + IntToStr(Index)); // 결과: 16 end; 실행 결과: "위치: 16" ('Delphi'.. 2025. 4. 30. Array.Exists()로 배열 조건 빠르게 검사하기 Array.Exists()로 배열 조건 빠르게 검사하기 C#의 Array.Exists() 메서드는 배열에 특정 조건을 만족하는 요소가 하나라도 존재하는지 간단하게 검사할 수 있는 방법입니다. 불필요한 반복문 없이 조건 검사를 간결하게 표현할 수 있어 유용합니다. using System; class Program { static void Main() { int[] numbers = { 3, 7, 9, 12, 15 }; bool hasEven = Array.Exists(numbers, n => n % 2 == 0); Console.WriteLine(hasEven ? "✅ 배열에 짝수가 있습니다." : ".. 2025. 4. 30. Length를 이용한 배열과 문자열 길이 확인 Length를 이용한 배열과 문자열 길이 확인 델파이에서는 Length 함수를 사용해 배열의 크기나 문자열의 길이를 쉽게 구할 수 있습니다. 이는 반복문 작성, 데이터 유효성 검사, 문자열 처리 등에 매우 기본적이면서 중요한 역할을 합니다. uses System.SysUtils; procedure LengthExample; var SampleText: string; Numbers: array of Integer; begin SampleText := 'Hello Delphi!'; ShowMessage('문자열 길이: ' + IntToStr(Length(SampleText))); // 결과: 13 SetLength(Numbers, 5); ShowMessage('배열 크기: ' +.. 2025. 4. 29. string.IsNullOrWhiteSpace()로 문자열 안전하게 검사하기 string.IsNullOrWhiteSpace()로 문자열 안전하게 검사하기 C#에서는 string.IsNullOrWhiteSpace() 메서드를 사용하면 문자열이 null, 빈 문자열("") 또는 공백만 있는 경우를 한 번에 검사할 수 있습니다. 조건문을 깔끔하게 만들고, 널 포인터 예외도 예방할 수 있어 매우 유용합니다 using System; class Program { static void Main() { string input = " "; if (string.IsNullOrWhiteSpace(input)) { Console.WriteLine("⚠️ 입력값이 비어있거나 공백입니다."); } .. 2025. 4. 29. Copy 함수를 사용한 문자열 일부 추출 Copy 함수를 사용한 문자열 일부 추출 델파이에서 문자열의 일부분을 추출할 때 Copy 함수를 사용하면 매우 쉽고 빠르게 원하는 부분을 잘라낼 수 있습니다. 텍스트 처리, 데이터 분석, 포맷 변환 등 다양한 상황에서 유용하게 활용됩니다. uses System.SysUtils; procedure CopyExample; var OriginalText, ExtractedText: string; begin OriginalText := 'Welcome to Delphi World!'; ExtractedText := Copy(OriginalText, 12, 6); // 12번째 문자부터 6글자 추출 ShowMessage('추출된 텍스트: ' + ExtractedText); end; Copy.. 2025. 4. 28. File.ReadAllText()로 파일 전체 읽기 File.ReadAllText()로 파일 전체 읽기 C#에서는 File.ReadAllText() 메서드를 사용하면 텍스트 파일 전체를 한 번에 간단하게 읽어올 수 있습니다. 짧은 텍스트 파일을 빠르게 읽어야 할 때 매우 유용합니다. using System; using System.IO; class Program { static void Main() { string filePath = "sample.txt"; if (File.Exists(filePath)) { string content = File.ReadAllText(filePath); Console.WriteLine("파일 내용:\n" + conte.. 2025. 4. 28. FindComponent를 활용한 동적 컴포넌트 접근 FindComponent를 활용한 동적 컴포넌트 접근 델파이에서는 FindComponent를 이용해 런타임 중 컴포넌트 이름을 문자열로 찾아 접근할 수 있습니다. 폼에 많은 컴포넌트가 있을 때 동적으로 제어하거나, 이름 규칙에 따라 그룹 작업을 할 때 유용합니다. procedure SetLabelCaptions; var I: Integer; Lbl: TLabel; begin for I := 1 to 5 do begin Lbl := TLabel(FindComponent('Label' + IntToStr(I))); if Assigned(Lbl) then Lbl.Caption := '항목 ' + IntToStr(I); end; end; FindComponent.. 2025. 4. 26. Guid로 전 세계에서 유일한 값 생성하기 Guid로 전 세계에서 유일한 값 생성하기 Guid(Globally Unique Identifier)는 거의 충돌이 발생하지 않는 고유 식별자를 생성할 수 있어, 데이터베이스 키, 파일명, 트랜잭션 ID 등 다양한 곳에 활용됩니다. using System; class Program { static void Main() { Guid id = Guid.NewGuid(); Console.WriteLine($"새로운 GUID: {id}"); } } 출력 결과 예시 새로운 GUID: 3f2504e0-4f89-11d3-9a0c-0305e82c3301 Guid.NewGuid()를 호출하면 새로운 고유 식별자가 생성됩니다. 128비트 크기로 구성되어, 전 세계 어디.. 2025. 4. 26. IfThen을 사용한 간결한 조건 처리 IfThen을 사용한 간결한 조건 처리 델파이의 IfThen 함수는 짧고 간결하게 조건에 따라 값을 선택할 수 있게 해주는 함수입니다. 전통적인 if..then..else 구문보다 한 줄로 표현할 수 있어 코드가 훨씬 깔끔해집니다. uses System.StrUtils; procedure IfThenExample; var UserLevel: Integer; ResultText: string; begin UserLevel := 2; ResultText := IfThen(UserLevel = 1, '관리자', '일반 사용자'); ShowMessage('사용자 권한: ' + ResultText); end; IfThen(조건, 참일 때 값, 거짓일 때 값) 형식 문자열 뿐 아니라 .. 2025. 4. 25. DateTime과 TimeSpan으로 시간 계산하기 DateTime과 TimeSpan으로 시간 계산하기 C#의 DateTime과 TimeSpan은 날짜 및 시간 관련 작업을 매우 정밀하고 직관적으로 처리할 수 있도록 도와줍니다. 기간 계산, 남은 시간 체크, 타임스탬프 기록 등에 자주 사용됩니다. using System; class Program { static void Main() { DateTime start = new DateTime(2025, 4, 1); DateTime end = DateTime.Now; TimeSpan duration = end - start; Console.WriteLine($"시작일: {start}"); Console.WriteLine(.. 2025. 4. 25. AnsiUpperCase와 AnsiLowerCase로 대소문자 변환 AnsiUpperCase와 AnsiLowerCase로 대소문자 변환 문자열을 대문자 또는 소문자로 변환할 때 AnsiUpperCase와 AnsiLowerCase 함수를 사용하면 빠르고 간편하게 처리할 수 있습니다. 로케일에 민감하지 않은 문자열 비교나 정렬을 할 때 특히 유용합니다. uses System.SysUtils; procedure ConvertCaseExample; var Original, UpperStr, LowerStr: string; begin Original := 'Delphi Is Great!'; UpperStr := AnsiUpperCase(Original); LowerStr := AnsiLowerCase(Original); ShowMessage('대문자:.. 2025. 4. 24. Environment 클래스로 시스템 정보 가져오기 Environment 클래스로 시스템 정보 가져오기 C#의 System.Environment 클래스는 운영 체제, 시스템 경로, 사용자 정보 등 다양한 환경 정보를 손쉽게 가져올 수 있도록 도와줍니다. 로그 기록, 시스템 체크, 경로 자동 설정 등에 매우 유용합니다. using System; class Program { static void Main() { Console.WriteLine("OS 버전: " + Environment.OSVersion); Console.WriteLine("사용자 이름: " + Environment.UserName); Console.WriteLine("머신 이름: " + Environment.MachineName);.. 2025. 4. 24. QuotedStr를 사용한 안전한 문자열 포장 QuotedStr를 사용한 안전한 문자열 포장 SQL 쿼리나 JSON 문자열 생성 시 문자열을 따옴표로 감싸야 할 경우가 자주 있습니다. 이때 QuotedStr 함수를 사용하면 자동으로 작은따옴표(')를 감싸고 내부에 있는 따옴표도 이스케이프 처리해줍니다. uses System.SysUtils; procedure QuotedStrExample; var UserInput, SQL: string; begin UserInput := 'O''Reilly'; SQL := 'SELECT * FROM Users WHERE Name = ' + QuotedStr(UserInput); ShowMessage(SQL); end; "SELECT * FROM Users WHERE Name = 'O''Rei.. 2025. 4. 23. readonly struct로 불변 값 타입 만들기 readonly struct로 불변 값 타입 만들기 C#의 readonly struct는 값 타입(Struct)의 불변성을 보장해주며, 성능과 안정성 모두를 고려할 수 있는 구조입니다. 수학, 그래픽, 좌표계 등에서 많이 활용됩니다. using System; public readonly struct Point { public int X { get; } public int Y { get; } public Point(int x, int y) { X = x; Y = y; } public double Length => Math.Sqrt(X * X + Y * Y); } class Program { static void Main() .. 2025. 4. 23. 이전 1 2 3 4 ··· 57 다음