Computer >> 컴퓨터 >  >> 프로그래밍 >> C#

C# Console.Clear() 메서드 – 콘솔 화면 지우기 완벽 가이드

C# Console.Clear() 메서드란?

C#에서 제공하는 Console.Clear() 메서드는 콘솔 버퍼와 콘솔 창에 표시된 모든 정보를 지우는 역할을 합니다. 이 메서드를 호출하면 화면에 출력되어 있던 내용이 모두 사라지고, 마치 새로운 콘솔 세션을 시작한 것처럼 화면이 깨끗하게 초기화됩니다.

구문

Console.Clear() 메서드의 구문은 다음과 같습니다.

public static void Clear ();

이 메서드는 매개변수를 받지 않으며, 반환값도 없습니다. 단순히 호출만 하면 콘솔 화면이 즉시 지워집니다.

예제 1: Console.Clear() 사용 전

먼저 Console.Clear() 메서드를 적용하기 전의 동작을 살펴보겠습니다. 아래 예제는 두 개의 URI를 생성하고 비교한 후 출력하는 코드입니다.

using System;
public class Demo {
    public static void Main(){
        Uri newURI1 = new Uri("https://www.tutorialspoint.com/");
        Console.WriteLine("URI = "+newURI1);
        Console.WriteLine("String representation = "+newURI1.ToString());
        Uri newURI2 = new Uri("https://www.tutorialspoint.com/jquery.htm#abcd");
        Console.WriteLine("\nURI = "+newURI2);
        Console.WriteLine("String representation = "+newURI2.ToString());
        if(newURI1.Equals(newURI2))
            Console.WriteLine("\nBoth the URIs are equal!");
        else
            Console.WriteLine("\nBoth the URIs aren't equal!");
        Uri res = newURI1.MakeRelativeUri(newURI2);
        Console.WriteLine("Relative uri = "+res);
    }
}

출력 결과

위 코드를 실행하면 다음과 같은 출력 결과가 표시됩니다.

URI = https://www.tutorialspoint.com/
String representation = https://www.tutorialspoint.com/
URI = https://www.tutorialspoint.com/jquery.htm#abcd
String representation = https://www.tutorialspoint.com/jquery.htm#abcd
Both the URIs aren't equal!
Relative uri = jquery.htm#abcd

예제 2: Console.Clear() 적용 후

이번에는 동일한 예제에 Console.Clear() 메서드를 추가해 보겠습니다. 코드 마지막 부분에 Console.Clear()를 호출하고 그 뒤에 새로운 문장을 출력합니다.

using System;
public class Demo {
    public static void Main(){
        Uri newURI1 = new Uri("https://www.tutorialspoint.com/");
        Console.WriteLine("URI = "+newURI1);
        Console.WriteLine("String representation = "+newURI1.ToString());
        Uri newURI2 = new Uri("https://www.tutorialspoint.com/jquery.htm#abcd");
        Console.WriteLine("\nURI = "+newURI2);
        Console.WriteLine("String representation = "+newURI2.ToString());
        if(newURI1.Equals(newURI2))
            Console.WriteLine("\nBoth the URIs are equal!");
        else
            Console.WriteLine("\nBoth the URIs aren't equal!");
        Uri res = newURI1.MakeRelativeUri(newURI2);
        Console.WriteLine("Relative uri = "+res);
        Console.Clear();
        Console.WriteLine("Console cleared now!");
    }
}

출력 결과

실행 결과를 보면 앞서 출력되었던 URI 관련 내용이 모두 사라지고, Console.Clear()가 호출된 이후의 문장만 화면에 남게 됩니다.

Console cleared now!

정리

Console.Clear() 메서드는 프로그램 실행 중 이전 출력 내용을 제거하고 화면을 정리할 때 유용하게 활용됩니다. 진행 상황을 갱신하거나 사용자에게 새로운 화면을 보여줘야 하는 콘솔 애플리케이션에서 특히 유용하니 참고하세요.