푸터 콘텐츠로 바로가기
.NET 도움말

C# New (개발자를 위한 작동 방식)

C#의 new 연산자 키워드는 다용도로, 언어의 여러 필수 기능을 제공합니다. 객체를 인스턴스화하는 것부터 상속된 멤버 숨기기에 이르기까지, 그 적용을 이해하는 것은 C# 개발의 효과를 위한 필수적입니다. 이 가이드에서는 각기 다른 new 키워드의 사용을 탐구하며, 그 힘과 유연성을 입증하는 명확한 예를 제공합니다. 이 가이드의 후반부에서는 IronSoftware의 IronPDF 라이브러리 개요도 탐구할 것입니다.

객체 인스턴스화 소개

객체 인스턴스화는 new 연산자가 클래스 또는 구조체의 인스턴스를 생성하는 과정입니다. C#에서는 주로 지정된 타입의 생성자를 호출하고, 새 객체를 위한 메모리를 할당하는 new 키워드를 사용하여 이를 달성합니다.

새로운 인스턴스 생성

객체의 인스턴스를 생성하려면 new 연산자 다음에 클래스 이름과 괄호 쌍을 사용합니다. 클래스에 매개변수를 받는 생성자가 있으면, 이 괄호 안에 인수를 제공해야 합니다.

public class Book
{
    public string Title { get; set; }

    public Book(string title)
    {
        Title = title;
    }
}

Book book = new Book("The C# Programming Language");
public class Book
{
    public string Title { get; set; }

    public Book(string title)
    {
        Title = title;
    }
}

Book book = new Book("The C# Programming Language");
Public Class Book
	Public Property Title() As String

	Public Sub New(ByVal title As String)
		Me.Title = title
	End Sub
End Class

Private book As New Book("The C# Programming Language")
$vbLabelText   $csharpLabel

기본 생성자와 매개변수 없는 생성자

기본 생성자는 클래스에 명시적으로 정의된 생성자가 없는 경우 C#에서 제공됩니다. 그러나 매개변수를 가진 생성자가 한 번 정의되면, 매개변수가 없는 생성자는 필요하다면 명시적으로 선언해야 합니다.

public class ExampleClass
{
    // Parameterless constructor
    public ExampleClass()
    {
        // Initialization code here
    }
}
public class ExampleClass
{
    // Parameterless constructor
    public ExampleClass()
    {
        // Initialization code here
    }
}
Public Class ExampleClass
	' Parameterless constructor
	Public Sub New()
		' Initialization code here
	End Sub
End Class
$vbLabelText   $csharpLabel

고급 객체 생성 기술

C#에서 객체 생성은 단순히 클래스를 인스턴스화하는 것 이상입니다; 이는 언어의 강력한 기능을 활용하여 더 효율적이고, 가독성이 높으며, 간결한 코드를 작성하는 관문입니다. 여기서는 배열 작업, 유형 활용, 객체 초기화를 사용하여 코딩 노력을 간소화하는 고급 기술을 탐구합니다.

배열과 컬렉션

C#에서 특정 배열 타입의 배열을 생성하는 것은 기본적인 기술이지만, 당신의 코딩 능력을 향상시키는 것은 그 미묘한 차이점들입니다. 새로운 키워드를 사용하여 배열을 인스턴스화하고, 배열의 유형과 포함할 요소의 수를 지정할 수 있습니다. 이것은 구조화된 방법으로 변수의 컬렉션을 관리하는 데 중요합니다. 기본 배열을 넘어, 새로운 키워드는 복잡한 데이터 구조를 수용할 수 있는 다차원 및 비정형 배열의 생성을 용이하게 합니다.

// Single-dimensional array
int[] numbers = new int[5]; // Initializes an array for 5 integers

// Multidimensional array
int[,] matrix = new int[3, 2]; // A 3x2 matrix

// Jagged array (an array of arrays)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns
// Single-dimensional array
int[] numbers = new int[5]; // Initializes an array for 5 integers

// Multidimensional array
int[,] matrix = new int[3, 2]; // A 3x2 matrix

// Jagged array (an array of arrays)
int[][] jaggedArray = new int[3][];
jaggedArray[0] = new int[4]; // First row has 4 columns
jaggedArray[1] = new int[5]; // Second row has 5 columns
jaggedArray[2] = new int[3]; // Third row has 3 columns
' Single-dimensional array
Dim numbers(4) As Integer ' Initializes an array for 5 integers

' Multidimensional array
Dim matrix(2, 1) As Integer ' A 3x2 matrix

' Jagged array (an array of arrays)
Dim jaggedArray(2)() As Integer
jaggedArray(0) = New Integer(3){} ' First row has 4 columns
jaggedArray(1) = New Integer(4){} ' Second row has 5 columns
jaggedArray(2) = New Integer(2){} ' Third row has 3 columns
$vbLabelText   $csharpLabel

익명 형식

익명 형식은 정식 클래스를 선언하는 오버헤드 없이 임시 데이터 구조가 필요한 상황에서 빛을 발합니다. 프로퍼티 초기화 구문을 가진 새로운 키워드를 사용하여 즉석에서 객체를 생성할 수 있습니다. 이 기능은 LINQ 쿼리에서 큰 객체에서 일부 프로퍼티를 선택하거나 특정 타입을 생성하지 않고 데이터를 빠르게 그룹화할 때 매우 유용합니다.

var person = new { Name = "Alice", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");

// In LINQ
var results = from p in people
              select new { p.Name, p.Age };
var person = new { Name = "Alice", Age = 30 };
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}");

// In LINQ
var results = from p in people
              select new { p.Name, p.Age };
Dim person = New With {
	Key .Name = "Alice",
	Key .Age = 30
}
Console.WriteLine($"Name: {person.Name}, Age: {person.Age}")

' In LINQ
Dim results = From p In people
	Select New With {
		Key p.Name,
		Key p.Age
	}
$vbLabelText   $csharpLabel

객체 초기화자

객체 초기화자는 매개변수가 있는 생성자를 호출하지 않고 클래스 인스턴스를 생성하고 즉시 해당 프로퍼티를 설정할 수 있는 구문적 편리함을 나타냅니다. 이는 코드의 가독성을 높일 뿐만 아니라 다양한 상황에 대한 여러 생성자의 필요성을 제거함으로써 오류 발생 가능성을 줄입니다. 객체 초기화자는 복잡한 객체를 다룰 때 특히 유용하며, 필요한 프로퍼티만 설정할 수 있게 합니다.

public class Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }
    public Point Location { get; set; }
}

Rectangle rect = new Rectangle
{
    Width = 100,
    Height = 50,
    Location = new Point { X = 0, Y = 0 }
};
public class Rectangle
{
    public int Width { get; set; }
    public int Height { get; set; }
    public Point Location { get; set; }
}

Rectangle rect = new Rectangle
{
    Width = 100,
    Height = 50,
    Location = new Point { X = 0, Y = 0 }
};
Public Class Rectangle
	Public Property Width() As Integer
	Public Property Height() As Integer
	Public Property Location() As Point
End Class

Private rect As New Rectangle With {
	.Width = 100,
	.Height = 50,
	.Location = New Point With {
		.X = 0,
		.Y = 0
	}
}
$vbLabelText   $csharpLabel

로컬 함수와 람다 표현식

C#은 코드의 유연성과 간결성을 강화하는 로컬 함수와 람다 표현식을 지원합니다.

로컬 함수

로컬 함수는 다른 메소드의 범위 내에서 정의된 메소드로, 코드 구성 및 기능 캡슐화에 강력한 도구로 작용합니다.

public void PerformOperation()
{
    int LocalFunction(int x)
    {
        return x * x;
    }
    Console.WriteLine(LocalFunction(5)); // Output: 25
}
public void PerformOperation()
{
    int LocalFunction(int x)
    {
        return x * x;
    }
    Console.WriteLine(LocalFunction(5)); // Output: 25
}
Public Sub PerformOperation()
'INSTANT VB TODO TASK: Local functions are not converted by Instant VB:
'	int LocalFunction(int x)
'	{
'		Return x * x;
'	}
	Console.WriteLine(LocalFunction(5)) ' Output: 25
End Sub
$vbLabelText   $csharpLabel

Lambda 표현식

람다 표현식은 명시적인 대리자 타입의 필요 없이 인라인 표현식 또는 메소드를 작성하는 간결한 방법을 제공합니다.

Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25
Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25
$vbLabelText   $csharpLabel

상속에서의 'new' 사용

클래스 상속에서 새로운 키워드는 상속된 멤버를 숨길 수 있으며, 파생 클래스가 기반 클래스와 동일한 이름을 가진 멤버를 도입할 수 있게 합니다.

상속된 멤버 숨기기

new를 사용하여 파생 클래스에서 멤버를 숨기는 것은 동일한 멤버를 재정의하지 않습니다; 대신, 이는 기반 클래스 버전과 구별되는 새로운 멤버를 도입합니다.

public class BaseClass
{
    public void Display()
    {
        Console.WriteLine("Base display");
    }
}

public class DerivedClass : BaseClass
{
    public new void Display()
    {
        Console.WriteLine("Derived display");
    }
}
public class BaseClass
{
    public void Display()
    {
        Console.WriteLine("Base display");
    }
}

public class DerivedClass : BaseClass
{
    public new void Display()
    {
        Console.WriteLine("Derived display");
    }
}
Public Class BaseClass
	Public Sub Display()
		Console.WriteLine("Base display")
	End Sub
End Class

Public Class DerivedClass
	Inherits BaseClass

	Public Shadows Sub Display()
		Console.WriteLine("Derived display")
	End Sub
End Class
$vbLabelText   $csharpLabel

제네릭과 함께하는 new 이해하기

제네릭은 C# 프로그래밍에서 추상화 수준을 도입하여, 개발자가 일반 타입에 대해 작동하는 클래스, 메소드, 인터페이스를 설계할 수 있도록 합니다. 제네릭을 새로운 키워드와 결합하면 타입을 동적으로 인스턴스화할 수 있어 코드 재사용성을 높이고 중복을 줄입니다.

제네릭 타입의 new() 제약 조건

new() 제약 조건은 제네릭 클래스 또는 메소드에서 타입 인수가 공용 매개변수 없는 생성자를 가져야 한다고 지정하는 새로운 키워드 사용의 초석입니다. 이 제약 조건을 통해 제네릭 타입의 인스턴스를 클래스나 메소드 내에서 생성할 수 있으며, 제네릭 클래스 및 메소드를 더욱 유연하고 강력하게 만듭니다.

public class Container<t> where T : new()
{
    public T CreateItem()
    {
        return new T();
    }
}
public class Container<t> where T : new()
{
    public T CreateItem()
    {
        return new T();
    }
}
Public Class Container(Of T As {New})
    Public Function CreateItem() As T
        Return New T()
    End Function
End Class
$vbLabelText   $csharpLabel

이 예에서는 Container가 매개변수가 없는 생성자를 가진 T의 인스턴스를 생성할 수 있습니다. 이 기능은 특정 타입을 사전에 알지 못하는 상황에서 객체 생성이 필요한 라이브러리나 프레임워크 개발 시 매우 소중합니다.

IronPDF 소개

IronPDF – PDF 생성 및 조작을 위한 C# 라이브러리는 PDF 파일과 작업하기 위해 C#의 기능을 사용하는 강력한 도구로 돋보입니다. IronPDF를 통합함으로써, 개발자는 HTML 문자열, 파일 또는 URL에서 프로그램적으로 새로운 PDF 문서를 생성하고, 기존 PDF를 조작하며, 콘텐츠를 추출할 수 있습니다. 이는 C#의 친숙한 구문을 통해 이루어지며, 객체 인스턴스화를 위한 새로운 키워드를 활용합니다.

IronPDF는 원래 레이아웃과 스타일을 정확히 보존하여 HTML을 PDF로 변환하는 데 탁월합니다. 보고서, 송장 및 설명서와 같은 웹 기반 콘텐츠에서 PDF를 생성하는 데 완벽합니다. HTML 파일, URL 및 원시 HTML 문자열에 대한 지원으로 IronPDF는 고품질의 PDF 문서를 쉽게 생성합니다.

using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
using IronPdf;

class Program
{
    static void Main(string[] args)
    {
        var renderer = new ChromePdfRenderer();

        // 1. Convert HTML String to PDF
        var htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>";
        var pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent);
        pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf");

        // 2. Convert HTML File to PDF
        var htmlFilePath = "path_to_your_html_file.html"; // Specify the path to your HTML file
        var pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath);
        pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf");

        // 3. Convert URL to PDF
        var url = "http://ironpdf.com"; // Specify the URL
        var pdfFromUrl = renderer.RenderUrlAsPdf(url);
        pdfFromUrl.SaveAs("URLToPDF.pdf");
    }
}
Imports IronPdf

Friend Class Program
	Shared Sub Main(ByVal args() As String)
		Dim renderer = New ChromePdfRenderer()

		' 1. Convert HTML String to PDF
		Dim htmlContent = "<h1>Hello, IronPDF!</h1><p>This is a PDF from an HTML string.</p>"
		Dim pdfFromHtmlString = renderer.RenderHtmlAsPdf(htmlContent)
		pdfFromHtmlString.SaveAs("HTMLStringToPDF.pdf")

		' 2. Convert HTML File to PDF
		Dim htmlFilePath = "path_to_your_html_file.html" ' Specify the path to your HTML file
		Dim pdfFromHtmlFile = renderer.RenderHtmlFileAsPdf(htmlFilePath)
		pdfFromHtmlFile.SaveAs("HTMLFileToPDF.pdf")

		' 3. Convert URL to PDF
		Dim url = "http://ironpdf.com" ' Specify the URL
		Dim pdfFromUrl = renderer.RenderUrlAsPdf(url)
		pdfFromUrl.SaveAs("URLToPDF.pdf")
	End Sub
End Class
$vbLabelText   $csharpLabel

코드 예제

using IronPdf;
using System;

namespace IronPdfExample
{
    class Program
    {
        static void Main(string[] args)
        {
            IronPdf.License.LicenseKey = "License-Key";

            // Create a new PDF document from HTML content
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>");

            // Save the PDF to a file
            string filePath = "HelloWorld.pdf";
            pdf.SaveAs(filePath);

            // Confirmation message
            Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\\{filePath}");
        }
    }
}
using IronPdf;
using System;

namespace IronPdfExample
{
    class Program
    {
        static void Main(string[] args)
        {
            IronPdf.License.LicenseKey = "License-Key";

            // Create a new PDF document from HTML content
            var renderer = new ChromePdfRenderer();
            var pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>");

            // Save the PDF to a file
            string filePath = "HelloWorld.pdf";
            pdf.SaveAs(filePath);

            // Confirmation message
            Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\\{filePath}");
        }
    }
}
Imports IronPdf
Imports System

Namespace IronPdfExample
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			IronPdf.License.LicenseKey = "License-Key"

			' Create a new PDF document from HTML content
			Dim renderer = New ChromePdfRenderer()
			Dim pdf = renderer.RenderHtmlAsPdf("<h1>Hello, World!</h1><p>This is a PDF generated from HTML using IronPDF.</p>")

			' Save the PDF to a file
			Dim filePath As String = "HelloWorld.pdf"
			pdf.SaveAs(filePath)

			' Confirmation message
			Console.WriteLine($"PDF file has been generated at: {Environment.CurrentDirectory}\{filePath}")
		End Sub
	End Class
End Namespace
$vbLabelText   $csharpLabel

이 클래스 Program 코드 예에서는 new IronPdf.ChromePdfRenderer()가 IronPDF 렌더러 객체의 인스턴스화를 보여줍니다. 이 객체는 그런 다음 HTML 문자열에서 새로운 PDF를 생성하는 데 사용되며, 타사 라이브러리와 C#의 객체 생성 패턴의 매끄러운 통합을 선보입니다. IronPDF는 클래스를 시작하는 데 새로운 키워드가 필요하므로, 객체 인스턴스화에 대해 배우고 C#의 고급 기능을 탐색하는 개발자에게 관련 있는 예시입니다.

결론

C#의 새로운 키워드는 객체 지향 프로그래밍의 초석으로, 개발자가 객체를 인스턴스화하고 상속을 관리하며, 정확하고 쉽게 제네릭을 활용할 수 있게 합니다. 이 가이드는 단순한 클래스 인스턴스 생성을 시작으로 익명 형식과 객체 초기화자 같은 고급 기능을 활용하는 실제 예제를 통해 새로운 키워드의 다재다능함과 힘을 보여줍니다.

IronPDF의 통합은 C#이 전통적인 응용 프로그램을 넘어 PDF 파일의 생성 및 조작까지 범위를 확장할 수 있음을 보여줍니다. IronPDF는 개발자가 기능을 탐구할 수 있는 무료 체험판 및 라이센스 옵션을 제공하며, 라이센스는 경쟁력 있는 가격에서 시작합니다.

자주 묻는 질문

C#에서 new 키워드는 어떻게 객체 인스턴스화를 용이하게 할까요?

C#에서 new 키워드는 클래스의 생성자를 호출하여 새로운 객체를 위한 메모리를 할당함으로써 객체 인스턴스화를 용이하게 합니다. 이는 클래스나 구조체의 인스턴스를 생성하는 데 필수적입니다.

C# 내 클래스 상속에서 new 키워드의 역할은 무엇입니까?

클래스 상속에서의 new 키워드는 파생 클래스가 상속된 멤버와 동일한 이름의 멤버를 도입하여 기본 클래스 멤버를 재정의하지 않고 숨길 수 있도록 합니다.

C#을 사용하여 HTML을 PDF로 변환하는 방법은 무엇인가요?

IronPDF의 기능을 사용하여 C#에서 HTML을 PDF로 변환할 수 있습니다. 이 라이브러리는 HTML 문자열과 파일을 PDF로 렌더링하여 원래 레이아웃과 스타일을 보존합니다.

C# 제네릭에서 new() 제약 조건의 목적은 무엇입니까?

C# 제네릭에서 new() 제약 조건은 타입 인수가 공용 매개변수가 없는 생성자가 있어야 함을 지정하여 클래스나 메서드 내에서 제네릭 타입의 인스턴스를 생성할 수 있게 합니다.

객체 초기화자는 C# 개발자에게 어떤 이점을 줄까요?

C#의 객체 초기화자는 개발자가 클래스의 인스턴스를 생성하고 그 속성을 하나의 문장에서 설정할 수 있게 하여 코드 가독성을 향상하고 여러 생성자가 필요 없도록 합니다.

C#에서 PDF를 생성하고 조작하는 방법은 무엇입니까?

IronPDF 라이브러리를 사용하여 C#에서 PDF를 생성하고 조작할 수 있습니다. 이 라이브러리는 HTML에서 PDF를 생성하고, 기존 PDF를 조작하며, C# 구문을 사용하여 콘텐츠를 추출하는 기능을 제공합니다.

C#의 익명 타입이란 무엇이며 언제 이를 사용할까요?

C#의 익명 타입은 공식적으로 클래스를 선언하지 않고도 경량의 임시 데이터 구조를 생성하는 데 사용됩니다. 이는 필요한 속성의 하위 집합만 필요한 LINQ 쿼리와 같은 시나리오에서 유용합니다.

C#에서 new 키워드는 서드파티 라이브러리 사용을 어떻게 향상시킬까요?

C#에서 new 키워드는 개발자가 이러한 라이브러리의 객체를 인스턴스화할 수 있게 하여, 예를 들어 HTML 소스에서 PDF를 생성하기 위해 IronPDF 객체를 생성하는 데 사용합니다.

제이콥 멜러, 팀 아이언 최고기술책임자
최고기술책임자

제이콥 멜러는 Iron Software의 최고 기술 책임자(CTO)이자 C# PDF 기술을 개척한 선구적인 엔지니어입니다. Iron Software의 핵심 코드베이스를 최초로 개발한 그는 창립 초기부터 회사의 제품 아키텍처를 설계해 왔으며, CEO인 캐머런 리밍턴과 함께 회사를 NASA, 테슬라, 그리고 전 세계 정부 기관에 서비스를 제공하는 50명 이상의 직원을 보유한 기업으로 성장시켰습니다.

제이콥은 맨체스터 대학교에서 토목공학 학사 학위(BEng)를 최우등으로 취득했습니다(1998~2001). 1999년 런던에서 첫 소프트웨어 회사를 설립하고 2005년 첫 .NET 컴포넌트를 개발한 후, 마이크로소프트 생태계 전반에 걸쳐 복잡한 문제를 해결하는 데 전문성을 발휘해 왔습니다.

그의 대표 제품인 IronPDF 및 Iron Suite .NET 라이브러리는 전 세계적으로 3천만 건 이상의 NuGet 설치 수를 기록했으며, 그의 핵심 코드는 전 세계 개발자들이 사용하는 다양한 도구에 지속적으로 활용되고 있습니다. 25년의 실무 경험과 41년의 코딩 전문성을 바탕으로, 제이콥은 차세대 기술 리더들을 양성하는 동시에 기업 수준의 C#, Java, Python PDF 기술 혁신을 주도하는 데 주력하고 있습니다.

아이언 서포트 팀

저희는 주 5일, 24시간 온라인으로 운영합니다.
채팅
이메일
전화해