C# New (jak to działa dla programistów)
Operator new w C# jest wszechstronny, sluzy do wielu istotnych funkcji w języku. Od tworzenia obiektow po ukrywanie odziedziczonych czlonkow, zrozumienie ich zastosowan jest kluczowe dla efektywnego rozwoju w C#. Ten przewodnik zglebia różne zastosowania slowa kluczowego new, dostarczając jasnych przykładów ilustrujacych jego moc i elastycznosc. W tej części przewodnika omówimy również przegląd biblioteki IronPDF na Iron Software.
Wstep do tworzenia obiektow
Inicjalizacja obiektu to proces, w którym operator new tworzy instancję klasy lub struktury. W C# jest to głównie osiagniete za pomoca slowa kluczowego new, ktore wywoluje konstruktor okreslonego typu i alokuje pamięć dla nowego obiektu.
Tworzenie instancji za pomoca new
Aby utworzyć instancję obiektu, po operatorze new umieszcza się nazwę klasy i parę nawiasów. Jeśli klasa ma konstruktor przyjmujacy parametry, w tym nawiasach musza zostac podane argumenty.
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")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")Domyslne i bezparametrowe konstruktory
C# dostarcza domyslny konstruktor, jeśli w klasie nie zdefiniowano zadnych konstruktorow. Jednak gdy zdefiniowano konstruktor z parametrami, trzeba jawnie zadeklarowac bezparametrowy konstruktor, jeśli jest potrzebny.
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 ClassPublic Class ExampleClass
' Parameterless constructor
Public Sub New()
' Initialization code here
End Sub
End ClassZaawansowane techniki tworzenia obiektow
W C#, tworzenie obiektow to nie tylko instancjowanie klas; to brama do wykorzystywania potężnych funkcjonalności języka dla bardziej wydajnego, czytelnego i zwięzłego kodu. Tutaj badamy zaawansowane techniki, takie jak praca z tablicami, wykorzystanie typow i stosowanie inicjalizatorow obiektow, aby usprawnic swoje wysilki w kodowaniu.
Tablice i kolekcje
Tworzenie tablic okreslonego typu tablicowego w C# to podstawowa umiejetnosc, ale to szczegóły podnosza twoje umiejetnosci programistyczne. Używając slowa kluczowego new, można zainstalować tablice, okreslajac ich typ i liczbe elementow, jakie powinny zawierać. To jest kluczowe do zarządzania kolekcjami zmiennych w uporzadkowany sposob. Poza podstawowymi tablicami, new ułatwia tworzenie tablic wielowymiarowych i postrzepionych, obslugujacych zlozone struktury danych.
// 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' 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 columnsTypy anonimowe
Typy anonimowe blyszcza w scenariuszach wymagajacych tymczasowych struktur danych bez narzutu związanego z deklarowaniem formalnej klasy. Używając new z skladnia inicjalizatora właściwości, można tworzyć obiekty na biezaco. Ta funkcja jest niezwykle przydatna w zapytaniach LINQ, gdzie potrzeba wybrania podzbioru właściwości z wiekszego obiektu lub do szybkiego grupowania danych bez tworzenia konkretnego typu.
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
}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
}Inicjalizatory obiektów
Inicjalizator obiektu to wygoda skladniowa, pozwalająca stworzyć instancje klasy i od razu ustawic jej właściwości bez wywolywania konstruktóra z parametrami. To nie tylko sprawia, ze kod jest bardziej czytelny, ale także zmniejsza prawdopodobienstwo błędów, eliminujac potrzebe wielu konstruktorow dla różnych scenariuszy. Inicjalizatory obiektow sa szczegółnie przydatne przy pracy z zalozonymi obiektami, pozwalając ustalic tylko potrzebne właściwości.
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
}
}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
}
}Funkcje lokalne i wyrazenia lambda
C# wspiera funkcje lokalne i wyrazenia lambda, zwiększając elastycznosc i zwięzłość kodu.
Funkcja lokalna
Funkcja lokalna to metoda zdefiniowana w zakresie innej metody, sluzy jako potężne narzędzie do organizowania kodu i kapsulacji funkcjonalności.
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 SubPublic 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 SubWyrażenia lambda
Wyrazenie lambda dostarcza zwięzly sposob na pisanie wyrazen lub metod inline bez potrzeby jawnych typow delegatow.
Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25Func<int, int> square = x => x * x;
Console.WriteLine(square(5)); // Output: 25Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25Dim square As Func(Of Integer, Integer) = Function(x) x * x
Console.WriteLine(square(5)) ' Output: 25Uzywanie 'new' w dziedziczeniu
W dziedziczeniu klas, new może ukrywac odziedziczonych czlonkow, pozwalając klasom pochodnym wprowadzić czlonkow o tej samej nazwie co ich bazowe klasy.
Ukrywanie odziedziczonych czlonkow
Użycie new do ukrycia członka w klasie pochodnej nie nadpisuje tego samego członka; zamiast tego, wprowadza nowy czlonek, ktory jest odrebny od wersji klasy bazowej.
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 ClassPublic 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 ClassZrozumienie new z generykami
Generyki wprowadzają poziom abstrakcji w programowaniu C#, pozwalając projektowac klasy, metody i interfejsy działajace na typach ogolnych. W połączeniu ze slowem kluczowym new, generyki pozwalają dynamicznie instancjowac typy, jeszcze bardziej poprawiając możliwość ponownego wykorzystania kodu i redukcje redundancji.
Ograniczenie new() w typie generycznym
Ograniczenie new() jest podstawa użycia new z generykami, specyfikujac, ze argument typu w klasie lub metodzie generycznej musi mieć publiczny bezparametrowy konstruktor. To ograniczenie pozwala tworzyć instancje typu generycznego w obrebie klasy lub metody, czyniac twoje klasy i metody generyczne bardziej elastycznymi i potężnymi.
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 ClassPublic Class Container(Of T As New)
Public Function CreateItem() As T
Return New T()
End Function
End ClassW tym przykładzie Container może tworzyć instancje T, pod warunkiem że T ma konstruktor bezparametrowy. Ta funkcjonalność jest nieoceniona przy tworzeniu bibliotek lub frameworkow, ktore wymagaja tworzenia obiektow, ale nie znaja z gory konkretnych typow.
Wprowadzenie do IronPDF
IronPDF – biblioteka C# do generowania i manipulacji PDF wyróznia sie jako potężne narzędzie wykorzystujące możliwości C# do pracy z plikami PDF. Dzięki włączeniu IronPDF, programiści mogą programowo tworzyć nowe dokumenty PDF z łańcuchów HTML, plików lub adresów URL, manipulować istniejącymi PDF-ami i wyodrębniać zawartość, wszystko za pomocą znanej składni C# i wykorzystując słowo kluczowe new do tworzenia obiektów.
IronPDF wyróżnia się w konwersji HTML do PDF, zapewniając precyzyjne zachowanie oryginalnych układów i stylów. Idealnie nadaje się do tworzenia plików PDF z treści internetowych, takich jak raporty, faktury i dokumentacja. Dzięki obsłudze plików HTML, adresów URL i surowych ciągów znaków HTML, IronPDF z łatwością tworzy wysokiej jakości dokumenty 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 ClassImports 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 ClassPrzykład kodu
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 NamespaceImports 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 NamespaceW tym fragmencie kodu Program, new IronPdf.ChromePdfRenderer() demonstruje inicjalizację obiektu renderera IronPDF. Ten obiekt jest następnie używany do tworzenia nowego PDF z łańcucha HTML, prezentując płynną integrację zewnętrznych bibliotek z wzorcami tworzenia obiektów w C#. IronPDF wymaga użycia słowa kluczowego new do inicjalizacji swoich klas, co czyni to odpowiednim przykładem dla deweloperów uczących się o tworzeniu obiektów i eksplorujących zaawansowane funkcje C#.
Wnioski
Słowo kluczowe new w C# jest fundamentem programowania zorientowanego obiektowo, umożliwiającym programistom tworzenie instancji obiektów, zarządzanie dziedziczeniem i precyzyjne oraz łatwe korzystanie z generyków. Przez praktyczne przykłady, od tworzenia prostych instancji klas po wykorzystanie zaawansowanych funkcji jak typy anonimowe i inicjalizatory obiektow, ten przewodnik demonstruje wszechstronność i moc new.
Integracja IronPDF pokazuje, jak C# może wykraczać poza tradycyjne aplikacje, pozwalając na generowanie i manipulowanie plikami PDF poprzez kod. IronPDF oferuje bezplatna wersje próbna i opcje licencyjne dla deweloperow, aby zbadac jego funkcjonalności, z licencjami zaczynajacymi sie od konkurencyjnej ceny.
Jacob Mellor jest Chief Technology Officer w Iron Software i wizjonerskim inżynierem, pionierem technologii C# PDF. Jako pierwotny deweloper głównej bazy kodowej Iron Software, kształtuje architekturę produktów firmy od jej początku, przekształcając ją wspólnie z CEO Cameron Rimington w firmę liczącą ponad 50 osób, obsługującą NASA, Teslę i światowe agencje rządowe.
Powiązane artykuły