GirişIntroduction

C# ("bkz. diyez") basit, modern, nesne odaklı ve tür açısından güvenli bir programlama dilidir.C# (pronounced "See Sharp") is a simple, modern, object-oriented, and type-safe programming language. C#, C ailesinin köklerine sahiptir ve C, C++ ve Java programcılarına hemen tanıdık gelecektir.C# has its roots in the C family of languages and will be immediately familiar to C, C++, and Java programmers. C#, Ecma International tarafından ECMA-334 _ standart ve ISO/IEC tarafından _ ıso/IEC 23270 standardı olarak standartlaştırılmıştır.C# is standardized by ECMA International as the ECMA-334 _ standard and by ISO/IEC as the _ ISO/IEC 23270 standard. .NET Framework için Microsoft 'un C# derleyicisi, bu standartların her ikisinin de uyumlu bir uygulamasıdır.Microsoft's C# compiler for the .NET Framework is a conforming implementation of both of these standards.

C#, nesne odaklı bir dildir, ancak c# buna ek olarak bileşen odaklı programlama için destek içerir.C# is an object-oriented language, but C# further includes support for component-oriented programming. Modern yazılım tasarımı giderek, yazılım bileşenlerini, kendi kendine içerilen ve kendi kendine açıklayan işlev paketleri biçiminde kullanır.Contemporary software design increasingly relies on software components in the form of self-contained and self-describing packages of functionality. Bu bileşenlere anahtar, özellikler, Yöntemler ve olaylar içeren bir programlama modeli sunduklarında; Bunlar, bileşen hakkında bildirime dayalı bilgiler sağlayan özniteliklere sahiptir; ve kendi belgelerini içerirler.Key to such components is that they present a programming model with properties, methods, and events; they have attributes that provide declarative information about the component; and they incorporate their own documentation. C#, bu kavramları doğrudan desteklemek için dil yapıları sağlar ve c#, yazılım bileşenlerinin oluşturulması ve kullanılması için çok doğal bir dil yapar.C# provides language constructs to directly support these concepts, making C# a very natural language in which to create and use software components.

Birçok C# özelliği sağlam ve dayanıklı uygulamalar oluşturmaya yardımcı olur: çöp toplama _, kullanılmayan nesneler tarafından kullanılan belleği otomatik olarak geri kazanır; _özel durum işleme_ , hata algılama ve kurtarmaya yönelik yapılandırılmış ve genişletilebilir bir yaklaşım sağlar; ve _ türü güvenli dilinin tasarımı, başlatılmamış değişkenlerden okumayı, sınırları ötesinde dizileri dizin haline getirmek veya Denetlenmemiş tür yayınları gerçekleştirmeyi olanaksız hale getirir.Several C# features aid in the construction of robust and durable applications: Garbage collection _ automatically reclaims memory occupied by unused objects; _exception handling_ provides a structured and extensible approach to error detection and recovery; and the _ type-safe design of the language makes it impossible to read from uninitialized variables, to index arrays beyond their bounds, or to perform unchecked type casts.

C# Birleşik bir tür sistemine sahiptir.C# has a unified type system. Ve gibi temel türler dahil olmak üzere tüm C# int türleri double , tek bir kök türünden devralınır object .All C# types, including primitive types such as int and double, inherit from a single root object type. Bu nedenle, tüm türler ortak işlemler kümesini paylaşır ve herhangi bir türdeki değerler tutarlı bir şekilde depolanabilir, taşınır ve çalıştırılabilir.Thus, all types share a set of common operations, and values of any type can be stored, transported, and operated upon in a consistent manner. Ayrıca, C# hem Kullanıcı tanımlı başvuru türlerini hem de değer türlerini destekler, bu da nesnelerin dinamik ayrılmasına ve basit yapıların satır içi depolamamasına olanak tanır.Furthermore, C# supports both user-defined reference types and value types, allowing dynamic allocation of objects as well as in-line storage of lightweight structures.

C# programlarının ve kitaplıklarının zaman içinde zaman içinde gelişebilmesini sağlamak için c# tasarımında sürüm oluşturma konusuna çok fazla vurgu konulmuştur.To ensure that C# programs and libraries can evolve over time in a compatible manner, much emphasis has been placed on versioning in C#'s design. Birçok programlama dili bu sorunla ilgileniyor ve sonuç olarak, bu dillerde yazılmış programlar, bağımlı kitaplıkların daha yeni sürümleri tanıtıldığında gerekenden çok daha fazla.Many programming languages pay little attention to this issue, and, as a result, programs written in those languages break more often than necessary when newer versions of dependent libraries are introduced. C# tasarımının sürüm oluşturma konuları tarafından doğrudan etkilenmiş olan yönleri virtual , ayrı ve override değiştiriciler, yöntem aşırı yükleme çözümlemesi kurallarını ve açık arabirim üyesi bildirimleri için desteği içerir.Aspects of C#'s design that were directly influenced by versioning considerations include the separate virtual and override modifiers, the rules for method overload resolution, and support for explicit interface member declarations.

Bu bölümün geri kalanında C# dilinin önemli özellikleri açıklanmaktadır.The rest of this chapter describes the essential features of the C# language. Sonraki bölümlerde, kuralları ve özel durumları ayrıntı yönelimli ve bazen matematik olarak anlasa da, bu bölüm, tamamlanma masrafında açıklık ve kısaltma açısından çok çaba harcar.Although later chapters describe rules and exceptions in a detail-oriented and sometimes mathematical manner, this chapter strives for clarity and brevity at the expense of completeness. Amaç, okuyucuya erken programların yazılmasına ve sonraki bölümlerin okunmasına yardımcı olacak dile bir giriş sunmaktır.The intent is to provide the reader with an introduction to the language that will facilitate the writing of early programs and the reading of later chapters.

Merhaba dünyaHello world

"Hello, World" programı, genellikle bir programlama dilini tanıtmak için kullanılır.The "Hello, World" program is traditionally used to introduce a programming language. Burada C# ' de yer verilmiştir:Here it is in C#:

using System;

class Hello
{
    static void Main() {
        Console.WriteLine("Hello, World");
    }
}

C# kaynak dosyaları genellikle dosya uzantısına sahiptir .cs .C# source files typically have the file extension .cs. "Hello, World" programının dosyada depolandığını varsayarak hello.cs , program komut satırı kullanılarak Microsoft C# derleyicisi ile derlenebilirAssuming that the "Hello, World" program is stored in the file hello.cs, the program can be compiled with the Microsoft C# compiler using the command line

csc hello.cs

adında bir çalıştırılabilir derleme üreten hello.exe .which produces an executable assembly named hello.exe. Bu uygulama tarafından çalıştırıldığında üretilen çıkış,The output produced by this application when it is run is

Hello, World

"Hello, World" programı, using ad alanına başvuran bir yönergeyle başlar System .The "Hello, World" program starts with a using directive that references the System namespace. Ad alanları, C# programlarının ve kitaplıklarının düzenlenmesi için hiyerarşik bir yol sağlar.Namespaces provide a hierarchical means of organizing C# programs and libraries. Ad alanları türler ve diğer ad alanlarını içerir — örneğin, System ad alanı programda başvurulan sınıf gibi bir dizi tür içerir Console ve ve gibi diğer ad alanları vardır IO Collections .Namespaces contain types and other namespaces—for example, the System namespace contains a number of types, such as the Console class referenced in the program, and a number of other namespaces, such as IO and Collections. usingVerilen bir ad alanına başvuruda bulunan bir yönerge, bu ad alanının üyesi olan türlerin nitelenmemiş kullanımını mümkün değildir.A using directive that references a given namespace enables unqualified use of the types that are members of that namespace. usingYönergesi nedeniyle program, Console.WriteLine için toplu olarak kullanabilir System.Console.WriteLine .Because of the using directive, the program can use Console.WriteLine as shorthand for System.Console.WriteLine.

Hello"Hello, World" programı tarafından belirtilen sınıf tek bir üyeye sahiptir, yöntemi adlı Main .The Hello class declared by the "Hello, World" program has a single member, the method named Main. MainYöntemi static değiştiriciyle birlikte bildirilmiştir.The Main method is declared with the static modifier. Örnek yöntemleri, anahtar sözcüğünü kullanarak belirli bir kapsayan nesne örneğine başvurabilir this , ancak statik yöntemler belirli bir nesneye başvuru olmadan çalışır.While instance methods can reference a particular enclosing object instance using the keyword this, static methods operate without reference to a particular object. Kurala göre, adlı statik bir yöntem, Main bir programın giriş noktası olarak görev yapar.By convention, a static method named Main serves as the entry point of a program.

Programın çıktısı, WriteLine Console ad alanındaki sınıfının yöntemi tarafından üretilir System .The output of the program is produced by the WriteLine method of the Console class in the System namespace. Bu sınıf, varsayılan olarak Microsoft C# derleyicisi tarafından otomatik olarak başvurulduğu .NET Framework sınıf kitaplıkları tarafından sağlanır.This class is provided by the .NET Framework class libraries, which, by default, are automatically referenced by the Microsoft C# compiler. C# ' ın kendi kendine ayrı bir çalışma zamanı kitaplığı olmadığına unutmayın.Note that C# itself does not have a separate runtime library. Bunun yerine .NET Framework, C# çalışma zamanı kitaplığıdır.Instead, the .NET Framework is the runtime library of C#.

Program yapısıProgram structure

C# ' deki temel kurumsal kavramlar Programlar _, _ad alanları_, _türler_, _Üyeler_ ve _derlemelerdir*.The key organizational concepts in C# are programs _, _namespaces*, types, members, and *assemblies*. C# programları bir veya daha fazla kaynak dosyadan oluşur.C# programs consist of one or more source files. Programlar, üyeleri içeren ve ad alanları halinde düzenlenebilen türleri bildirir.Programs declare types, which contain members and can be organized into namespaces. Sınıflar ve arabirimler tür örnekleridir.Classes and interfaces are examples of types. Alanlar, Yöntemler, Özellikler ve olaylar üye örnekleridir.Fields, methods, properties, and events are examples of members. C# programları derlendiğinde, fiziksel olarak derlemeler halinde paketlenir.When C# programs are compiled, they are physically packaged into assemblies. Derlemeler genellikle dosya uzantısına sahiptir .exe veya .dll uygulamalar veya _ Kitaplıklar * ' ı uygulayıp uygulamadığına bağlı olarak.Assemblies typically have the file extension .exe or .dll, depending on whether they implement applications or _*libraries**.

ÖrnekteThe example

using System;

namespace Acme.Collections
{
    public class Stack
    {
        Entry top;

        public void Push(object data) {
            top = new Entry(top, data);
        }

        public object Pop() {
            if (top == null) throw new InvalidOperationException();
            object result = top.data;
            top = top.next;
            return result;
        }

        class Entry
        {
            public Entry next;
            public object data;
    
            public Entry(Entry next, object data) {
                this.next = next;
                this.data = data;
            }
        }
    }
}

adlı bir ad alanında adında bir sınıf bildirir Stack Acme.Collections .declares a class named Stack in a namespace called Acme.Collections. Bu sınıfın tam adı Acme.Collections.Stack .The fully qualified name of this class is Acme.Collections.Stack. Sınıf birçok üye içerir: adlı bir alan top , ve adlı iki yöntem Push Pop ve adlı bir iç içe sınıf Entry .The class contains several members: a field named top, two methods named Push and Pop, and a nested class named Entry. EntrySınıf daha fazla üç üye içerir: adlı alan next , adlı alan data ve Oluşturucu.The Entry class further contains three members: a field named next, a field named data, and a constructor. Örneğin kaynak kodunun dosyada depolandığını varsayarak acme.cs , komut satırıAssuming that the source code of the example is stored in the file acme.cs, the command line

csc /t:library acme.cs

örneği bir kitaplık (bir giriş noktası olmayan kod) olarak derler Main ve adında bir derleme oluşturur acme.dll .compiles the example as a library (code without a Main entry point) and produces an assembly named acme.dll.

Derlemeler, *ara dil _ (IL) yönergeleri biçiminde yürütülebilir kod ve _ metadata * biçiminde sembolik bilgiler içerir.Assemblies contain executable code in the form of Intermediate Language _ (IL) instructions, and symbolic information in the form of _metadata**. Yürütülmeden önce, bir derlemedeki IL kodu, .NET ortak dil çalışma zamanının tam zamanında (JıT) derleyicisi tarafından otomatik olarak işlemciye özgü koda dönüştürülür.Before it is executed, the IL code in an assembly is automatically converted to processor-specific code by the Just-In-Time (JIT) compiler of .NET Common Language Runtime.

Bir derleme, hem kodu hem de meta verileri içeren işlevsellikten oluşan bir birim olduğundan, #include C# dilinde yönergeler ve başlık dosyaları gerekmez.Because an assembly is a self-describing unit of functionality containing both code and metadata, there is no need for #include directives and header files in C#. Belirli bir derlemede yer alan ortak türler ve Üyeler, yalnızca program derlenirken bu derlemeye başvurarak bir C# programında kullanılabilir hale getirilir.The public types and members contained in a particular assembly are made available in a C# program simply by referencing that assembly when compiling the program. Örneğin, bu program Acme.Collections.Stack derlemeden sınıfını kullanır acme.dll :For example, this program uses the Acme.Collections.Stack class from the acme.dll assembly:

using System;
using Acme.Collections;

class Test
{
    static void Main() {
        Stack s = new Stack();
        s.Push(1);
        s.Push(10);
        s.Push(100);
        Console.WriteLine(s.Pop());
        Console.WriteLine(s.Pop());
        Console.WriteLine(s.Pop());
    }
}

Program dosyada depolanıyorsa test.cs , test.cs derlendikten sonra acme.dll derlemeye derleyicinin seçeneği kullanılarak başvurulabilir /r :If the program is stored in the file test.cs, when test.cs is compiled, the acme.dll assembly can be referenced using the compiler's /r option:

csc /r:acme.dll test.cs

Bu, çalıştırıldığında bir çalıştırılabilir derleme oluşturur; Bu, test.exe çalıştırıldığında çıktıyı üretir:This creates an executable assembly named test.exe, which, when run, produces the output:

100
10
1

C#, bir programın kaynak metninin birkaç kaynak dosyada depolanmasına izin verir.C# permits the source text of a program to be stored in several source files. Çok sayfalı bir C# programı derlendiğinde, tüm kaynak dosyaları birlikte işlenir ve kaynak dosyalar birbirini tamamen başvurabilir. kavramsal olarak, tüm kaynak dosyaları işlenmek üzere bir büyük dosyada birleştirilmiş olur.When a multi-file C# program is compiled, all of the source files are processed together, and the source files can freely reference each other—conceptually, it is as if all the source files were concatenated into one large file before being processed. Daha az sayıda özel durum, bildirim sırası çok önemli olduğundan, C# ' ta ileri bildirimlere hiçbir şekilde gerek yoktur.Forward declarations are never needed in C# because, with very few exceptions, declaration order is insignificant. C#, kaynak dosyayı yalnızca bir ortak tür bildirmek üzere sınırlamaz veya kaynak dosyanın adını kaynak dosyada belirtilen bir türle eşleşecek şekilde gerektirmez.C# does not limit a source file to declaring only one public type nor does it require the name of the source file to match a type declared in the source file.

Türler ve değişkenlerTypes and variables

C# içinde iki tür tür vardır: *değer türleri _ ve _ başvuru türleri *.There are two kinds of types in C#: value types _ and _reference types**. Değer türlerinin değişkenleri doğrudan verilerini içerir, ancak başvuru türündeki değişkenler verilerine başvuruları depolar, ikincisi ise nesneler olarak bilinir.Variables of value types directly contain their data whereas variables of reference types store references to their data, the latter being known as objects. Başvuru türleriyle, iki değişkenin aynı nesneye başvurması ve bu nedenle bir değişkende işlemler için diğer değişken tarafından başvurulan nesneyi etkilemesi mümkündür.With reference types, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. Değer türleriyle, her biri kendi verilerinin kopyasına sahiptir ve bir üzerindeki işlemler, diğerini ( ref ve parametre değişkenleri hariç) etkileyecek şekilde mümkün değildir out .With value types, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other (except in the case of ref and out parameter variables).

C# ' nin değer türleri, basit türler _, _sabit listesi türleri_, _yapı türleri_ ve _null yapılabilir türlere_ daha da bölünür ve C# ' nin başvuru türleri, _Sınıf türlerine_, _arabirim türlerine_, _dizi türlerine*_ ve _ *temsilci türlerine daha fazla bölünmüştür.C#'s value types are further divided into simple types _, _enum types_, _struct types_, and _nullable types_, and C#'s reference types are further divided into _class types_, _interface types_, _array types_, and _delegate types**.

Aşağıdaki tabloda C# tür sistemine genel bir bakış sağlanmaktadır.The following table provides an overview of C#'s type system.

KategoriCategory AçıklamaDescription
Değer türleriValue types Basit türlerSimple types İmzalanan integral: sbyte , short , int , longSigned integral: sbyte, short, int, long
İşaretsiz integral: byte , ushort , uint , ulongUnsigned integral: byte, ushort, uint, ulong
Unicode karakterler: charUnicode characters: char
IEEE kayan nokta: float , doubleIEEE floating point: float, double
Yüksek duyarlıklı ondalık: decimalHigh-precision decimal: decimal
Boolean boolBoolean: bool
Sabit listesi türleriEnum types Formun Kullanıcı tanımlı türleri enum E {...}User-defined types of the form enum E {...}
Yapı türleriStruct types Formun Kullanıcı tanımlı türleri struct S {...}User-defined types of the form struct S {...}
Null atanabilir türlerNullable types Bir değere sahip diğer tüm değer türlerinin uzantıları nullExtensions of all other value types with a null value
Başvuru türleriReference types Sınıf türleriClass types Diğer tüm türlerin Ultimate temel sınıfı: objectUltimate base class of all other types: object
Unicode dizeleri: stringUnicode strings: string
Formun Kullanıcı tanımlı türleri class C {...}User-defined types of the form class C {...}
Arabirim türleriInterface types Formun Kullanıcı tanımlı türleri interface I {...}User-defined types of the form interface I {...}
Dizi türleriArray types Tek ve çok boyutlu, örneğin int[] ve int[,]Single- and multi-dimensional, for example, int[] and int[,]
Temsilci türleriDelegate types Formun Kullanıcı tanımlı türleri örn. delegate int D(...)User-defined types of the form e.g. delegate int D(...)

Sekiz integral türü, imzalanmış veya imzasız biçimde 8 bit, 16 bit, 32-bit ve 64 bit değerleri için destek sağlar.The eight integral types provide support for 8-bit, 16-bit, 32-bit, and 64-bit values in signed or unsigned form.

İki kayan nokta türü ve, float double 32-bit tek duyarlıklı ve 64-bit ÇIFT duyarlıklı IEEE 754 biçimleri kullanılarak temsil edilir.The two floating point types, float and double, are represented using the 32-bit single-precision and 64-bit double-precision IEEE 754 formats.

decimalTürü, finansal ve parasal hesaplamalar için uygun olan 128 bitlik bir veri türüdür.The decimal type is a 128-bit data type suitable for financial and monetary calculations.

C# bool türü, Boole değerlerini (veya olan değerler) temsil etmek için kullanılır true false .C#'s bool type is used to represent boolean values—values that are either true or false.

C# ' de karakter ve dize işleme Unicode kodlaması kullanır.Character and string processing in C# uses Unicode encoding. charTür BIR UTF-16 kod birimini temsil eder ve string tür bir UTF-16 kod birimi dizisini temsil eder.The char type represents a UTF-16 code unit, and the string type represents a sequence of UTF-16 code units.

Aşağıdaki tabloda, C# ' nin sayısal türleri özetlenmektedir.The following table summarizes C#'s numeric types.

KategoriCategory BitsBits TürType Aralık/duyarlıkRange/Precision
İmzalanan integralSigned integral 88 sbyte -128... 127-128...127
1616 short -32768... 32, 767-32,768...32,767
3232 int -2147483648... 2, 147, 483, 647-2,147,483,648...2,147,483,647
6464 long -9223372036854775808... 9, 223, 372, 036, 854, 775, 807-9,223,372,036,854,775,808...9,223,372,036,854,775,807
İşaretsiz integralUnsigned integral 88 byte 0... 2550...255
1616 ushort 0... 65,0...65,535
3232 uint 0... 4, 294, 967, 2950...4,294,967,295
6464 ulong 0... 18, 446,, 073, 709, 551, 6150...18,446,744,073,709,551,615
Kayan noktaFloating point 3232 float 1,5 × 10 ^ − 45 ila 3,4 × 10 ^ 38, 7 basamaklı duyarlık1.5 × 10^−45 to 3.4 × 10^38, 7-digit precision
6464 double 5,0 × 10 ^ − 324 ila 1,7 × 10 ^ 308, 15 basamaklı duyarlık5.0 × 10^−324 to 1.7 × 10^308, 15-digit precision
OndalıkDecimal 128128 decimal 1,0 × 10 ^ − 28 ila 7,9 × 10 ^ 28, 28 basamaklı duyarlık1.0 × 10^−28 to 7.9 × 10^28, 28-digit precision

C# programları yeni türler oluşturmak için tür bildirimleri kullanır.C# programs use type declarations to create new types. Tür bildiriminde yeni türün adı ve üyeleri belirtilir.A type declaration specifies the name and the members of the new type. C# tür kategorilerinin sayısı Kullanıcı tarafından tanımlanabilir: sınıf türleri, yapı türleri, arabirim türleri, sabit listesi türleri ve temsilci türleri.Five of C#'s categories of types are user-definable: class types, struct types, interface types, enum types, and delegate types.

Bir sınıf türü, veri üyeleri (alanlar) ve işlev üyeleri (Yöntemler, Özellikler ve diğerleri) içeren bir veri yapısını tanımlar.A class type defines a data structure that contains data members (fields) and function members (methods, properties, and others). Sınıf türleri, tek devralma ve çok biçimlilik destekler, türetilmiş sınıfların temel sınıfları genişletebileceği ve özelleştireceği mekanizmalar.Class types support single inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize base classes.

Yapı türü, veri üyeleri ve işlev üyeleri olan bir yapıyı temsil eden bir sınıf türüne benzerdir.A struct type is similar to a class type in that it represents a structure with data members and function members. Ancak, sınıfların aksine yapılar değer türlerdir ve yığın ayırmayı gerektirmez.However, unlike classes, structs are value types and do not require heap allocation. Yapı türleri Kullanıcı tarafından belirtilen devralmayı desteklemez ve tüm yapı türleri örtülü olarak türünden devralınır object .Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

Arabirim türü, bir sözleşmeyi adlandırılmış bir ortak işlev üyeleri kümesi olarak tanımlar.An interface type defines a contract as a named set of public function members. Arabirim uygulayan bir sınıf veya yapı, arabirimin işlev üyelerinin uygulamalarını sağlamalıdır.A class or struct that implements an interface must provide implementations of the interface's function members. Bir arabirim birden çok temel arabirimden devralınabilir ve bir sınıf ya da yapı birden çok arabirim uygulayabilir.An interface may inherit from multiple base interfaces, and a class or struct may implement multiple interfaces.

Bir temsilci türü, belirli bir parametre listesi ve dönüş türü olan yöntemlere yapılan başvuruları temsil eder.A delegate type represents references to methods with a particular parameter list and return type. Temsilciler, yöntemleri değişkenlere atanabilecek ve parametre olarak geçirilen varlıklar olarak işleme olanağı tanır.Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Temsilciler, bazı diğer dillerde bulunan işlev işaretçileri kavramına benzerdir, ancak işlev işaretçilerinden farklı olarak Temsilciler nesne yönelimli ve tür açısından güvenlidir.Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe.

Sınıf, yapı, arabirim ve temsilci türleri tüm genel türleri destekler ve diğer türlerle parametrelenebilir.Class, struct, interface and delegate types all support generics, whereby they can be parameterized with other types.

Sabit listesi türü, adlandırılmış sabitleri olan ayrı bir türdür.An enum type is a distinct type with named constants. Her numaralandırma türünün, sekiz integral türünden biri olması gereken temel bir türü vardır.Every enum type has an underlying type, which must be one of the eight integral types. Bir sabit listesi türünün değer kümesi, temel alınan türün değerleri kümesiyle aynıdır.The set of values of an enum type is the same as the set of values of the underlying type.

C#, herhangi bir türdeki tek ve çok boyutlu dizileri destekler.C# supports single- and multi-dimensional arrays of any type. Yukarıda listelenen türlerin aksine,, kullanılmadan önce dizi türlerinin bildirilmesini gerektirmez.Unlike the types listed above, array types do not have to be declared before they can be used. Bunun yerine, dizi türleri Köşeli parantezlerle bir tür adı izleyerek oluşturulur.Instead, array types are constructed by following a type name with square brackets. Örneğin, int[] tek boyutlu bir diziyse int , iki boyutlu bir dizidir ve tek boyutlu int[,] int int[][] dizilerinin tek boyutlu dizilerdir int .For example, int[] is a single-dimensional array of int, int[,] is a two-dimensional array of int, and int[][] is a single-dimensional array of single-dimensional arrays of int.

Null yapılabilir türler, kullanılmadan önce de bildirilemez.Nullable types also do not have to be declared before they can be used. Her null yapılamayan değer türü için T , karşılık gelen bir null yapılabilir tür vardır T? ve bu, ek bir değer tutabilir null .For each non-nullable value type T there is a corresponding nullable type T?, which can hold an additional value null. Örneğin, int? herhangi bir 32 bit tamsayı veya değeri tutabilecek bir türdür null .For instance, int? is a type that can hold any 32 bit integer or the value null.

C# tür sistemi, herhangi bir türden bir değer bir nesne olarak işlenemeyeceği şekilde birleştirilmiştir.C#'s type system is unified such that a value of any type can be treated as an object. C# içindeki her tür doğrudan veya dolaylı olarak object sınıf türünden türetilir ve object tüm türlerin en son temel sınıfıdır.Every type in C# directly or indirectly derives from the object class type, and object is the ultimate base class of all types. Başvuru türlerinin değerleri, yalnızca değerleri tür olarak görüntüleyerek nesne olarak değerlendirilir object .Values of reference types are treated as objects simply by viewing the values as type object. Değer türlerinin değerleri, *kutulama _ ve _ kutudan çıkarma * işlemleri gerçekleştirerek nesneler olarak değerlendirilir.Values of value types are treated as objects by performing boxing _ and _ unboxing operations. Aşağıdaki örnekte, bir değeri öğesine int dönüştürülüp object öğesine yeniden döndürülür int .In the following example, an int value is converted to object and back again to int.

using System;

class Test
{
    static void Main() {
        int i = 123;
        object o = i;          // Boxing
        int j = (int)o;        // Unboxing
    }
}

Değer türünde bir değer türüne dönüştürüldüğünde object , "Box" olarak da bilinen bir nesne örneği değeri tutacak şekilde ayrılır ve değer bu kutuya kopyalanır.When a value of a value type is converted to type object, an object instance, also called a "box," is allocated to hold the value, and the value is copied into that box. Buna karşılık, bir object Başvuru bir değer türüne dönüştürülzaman, başvurulan nesnenin doğru değer türünün bir kutusu olması ve denetim başarılı olursa, kutudaki değer kopyalanır.Conversely, when an object reference is cast to a value type, a check is made that the referenced object is a box of the correct value type, and, if the check succeeds, the value in the box is copied out.

C# ' nin Birleşik tür sistemi etkin bir şekilde değer türlerinin "isteğe bağlı" nesneler olabileceği anlamına gelir.C#'s unified type system effectively means that value types can become objects "on demand." Birleşme nedeniyle, türü kullanan genel amaçlı kitaplıklar, object başvuru türleri ve değer türleriyle birlikte kullanılabilir.Because of the unification, general-purpose libraries that use type object can be used with both reference types and value types.

C# ' de alanlar, dizi öğeleri, yerel değişkenler ve parametreler gibi çeşitli türlerde değişkenler vardır.There are several kinds of variables in C#, including fields, array elements, local variables, and parameters. Değişkenler, depolama konumlarını temsil eder ve her değişken, aşağıdaki tabloda gösterildiği gibi, değişkende hangi değerlerin depolanabileceğini belirleyen bir tür içerir.Variables represent storage locations, and every variable has a type that determines what values can be stored in the variable, as shown by the following table.

Değişken türüType of Variable Olası IçeriklerPossible Contents
Null yapılamayan değer türüNon-nullable value type Bu tam türden bir değerA value of that exact type
Null yapılabilir değer türüNullable value type Null değer veya bu tam tür değeriA null value or a value of that exact type
object Bir null başvurusu, herhangi bir başvuru türünün nesnesine başvuru veya herhangi bir değer türünün paketlenmiş değerine başvuruA null reference, a reference to an object of any reference type, or a reference to a boxed value of any value type
Sınıf türüClass type Null başvurusu, bu sınıf türünün bir örneğine başvuru veya bu sınıf türünden türetilmiş bir sınıfın örneğine başvuruA null reference, a reference to an instance of that class type, or a reference to an instance of a class derived from that class type
Arabirim türüInterface type Null başvurusu, bu arabirim türünü uygulayan bir sınıf türü örneğine başvuru veya bu arabirim türünü uygulayan bir değer türünün paketlenmiş değerine başvuruA null reference, a reference to an instance of a class type that implements that interface type, or a reference to a boxed value of a value type that implements that interface type
Dizi türüArray type Null başvuru, bu dizi türünün bir örneğine başvuru veya uyumlu bir dizi türü örneğine başvuruA null reference, a reference to an instance of that array type, or a reference to an instance of a compatible array type
Temsilci türüDelegate type Bu temsilci türünün bir örneğine null başvuru veya başvuruA null reference or a reference to an instance of that delegate type

İfadelerExpressions

İfadeler _, _işlenenler_ ve _işleçlerden*_ oluşturulur.Expressions _ are constructed from _operands_ and _operators*_. Bir ifadenin işleçleri, işlenenlerin hangi işlemleri uygulanacağını gösterir.The operators of an expression indicate which operations to apply to the operands. İşleç örnekleri,, + , - _ ve içerir / new .Examples of operators include +, -, _, /, and new. İşlenenlerin örnekleri, sabit değerleri, alanları, yerel değişkenleri ve ifadeleri içerir.Examples of operands include literals, fields, local variables, and expressions.

Bir ifade birden çok işleç içerdiğinde, işleçlerin *önceliği _, bağımsız işleçlerin değerlendirildiği sırayı denetler.When an expression contains multiple operators, the *precedence _ of the operators controls the order in which the individual operators are evaluated. Örneğin, x + y _ z x + (y * z) * işleç işleçten daha yüksek önceliğe sahip olduğu için ifade değerlendirilir + .For example, the expression x + y _ z is evaluated as x + (y * z) because the * operator has higher precedence than the + operator.

Çoğu işleç aşırı yüklenebilir.Most operators can be overloaded. İşleç aşırı yüklemesi, Kullanıcı tanımlı operatör uygulamalarının bir veya her ikisinin de Kullanıcı tanımlı sınıf veya yapı türünde olduğu işlemler için belirtilmesine izin verir.Operator overloading permits user-defined operator implementations to be specified for operations where one or both of the operands are of a user-defined class or struct type.

Aşağıdaki tabloda, işleç kategorilerinin en yüksekten en düşüğe öncelik sırasına göre listelenmesi için C# işleçleri özetlenmektedir.The following table summarizes C#'s operators, listing the operator categories in order of precedence from highest to lowest. Aynı kategorideki işleçler eşit önceliğe sahiptir.Operators in the same category have equal precedence.

KategoriCategory ExpressionExpression AçıklamaDescription
BirincilPrimary x.m Üye erişimiMember access
x(...) Yöntem ve temsilci çağırmaMethod and delegate invocation
x[...] Dizi ve dizinleyici erişimiArray and indexer access
x++ Artırım sonrasıPost-increment
x-- Azaltım sonrasıPost-decrement
new T(...) Nesne ve temsilci oluşturmaObject and delegate creation
new T(...){...} Başlatıcı ile nesne oluşturmaObject creation with initializer
new {...} Anonim nesne BaşlatıcısıAnonymous object initializer
new T[...] Dizi oluşturmaArray creation
typeof(T) System.Typeİçin nesne alTObtain System.Type object for T
checked(x) İşaretli bağlamında ifade değerlendirmeEvaluate expression in checked context
unchecked(x) İşaretlenmemiş bağlamında ifade değerlendirmeEvaluate expression in unchecked context
default(T) Türün varsayılan değerini Al TObtain default value of type T
delegate {...} Anonim işlevi (anonim yöntemi)Anonymous function (anonymous method)
BirliUnary +x KimlikIdentity
-x NegatifNegation
!x Mantıksal değillemeLogical negation
~x Bitwise olumsuzlamaBitwise negation
++x Artırım öncesiPre-increment
--x Azaltım öncesiPre-decrement
(T)x Açıkça x türe Dönüştür TExplicitly convert x to type T
await x Zaman uyumsuz olarak işlemin tamamlanmasını bekleyin xAsynchronously wait for x to complete
ÇarpımsalMultiplicative x * y ÇarpmaMultiplication
x / y BölmeDivision
x % y KalanRemainder
ToplamsalAdditive x + y Toplama, dize bitiştirme, temsilci birleşimiAddition, string concatenation, delegate combination
x - y Çıkarma, temsilci kaldırmaSubtraction, delegate removal
ShiftShift x << y Sola kaydırmaShift left
x >> y Sağa kaydırmaShift right
İlişkisel ve tür testiRelational and type testing x < y KüçüktürLess than
x > y BüyüktürGreater than
x <= y Küçüktür veya eşittirLess than or equal
x >= y Büyüktür veya eşittirGreater than or equal
x is T true x Bir ise T , false tersi durumda döndürünReturn true if x is a T, false otherwise
x as T Dönüş x olarak yazılmış T veya null x``TReturn x typed as T, or null if x is not a T
EşitlikEquality x == y EşittirEqual
x != y Eşit değildirNot equal
Mantıksal VELogical AND x & y Tamsayı bit düzeyinde ve, Boolean mantıksal veInteger bitwise AND, boolean logical AND
Mantıksal XORLogical XOR x ^ y Tamsayı bit düzeyinde XOR, Boolean mantıksal XORInteger bitwise XOR, boolean logical XOR
Mantıksal EĞERLogical OR x | y Tamsayı bit düzeyinde OR, Boolean mantıksal veyaInteger bitwise OR, boolean logical OR
Koşullu VEConditional AND x && y yYalnızca şu durumlarda x değerlendirilirtrueEvaluates y only if x is true
Koşullu VEYAConditional OR x || y yYalnızca şu durumlarda x değerlendirilirfalseEvaluates y only if x is false
Null birleşimNull coalescing x ?? y , Değilse y olarak x değerlendirilir null xEvaluates to y if x is null, to x otherwise
KoşulluConditional x ? y : z Olup y olmadığını x değerlendirir true z x``falseEvaluates y if x is true, z if x is false
Atama veya anonim işlevAssignment or anonymous function x = y AtamaAssignment
x op= y Bileşik atama; Desteklenen işleçler *= /= %= += şunlardır -= <<= >>= &= ^=|=Compound assignment; supported operators are *= /= %= += -= <<= >>= &= ^= |=
(T x) => y Anonim işlevi (lambda ifadesi)Anonymous function (lambda expression)

DeyimlerStatements

Bir programın eylemleri deyimler kullanılarak ifade edilir.The actions of a program are expressed using statements. C#, gömülü deyimler açısından tanımlanmış bir dizi farklı sayıda ifadeyi destekler.C# supports several different kinds of statements, a number of which are defined in terms of embedded statements.

Bir blok , tek bir ifadeye izin verilen bağlamlarda birden çok deyimin yazılmasına izin verir.A block permits multiple statements to be written in contexts where a single statement is allowed. Bir blok, sınırlayıcılar ve arasında yazılmış deyimler listesinden oluşur { } .A block consists of a list of statements written between the delimiters { and }.

Bildirim deyimleri yerel değişkenleri ve sabitleri bildirmek için kullanılır.Declaration statements are used to declare local variables and constants.

İfade deyimleri , ifadeleri değerlendirmek için kullanılır.Expression statements are used to evaluate expressions. Deyim olarak kullanılabilecek ifadeler, yöntem etkinleştirmeleri, işleci kullanılarak nesne ayırmaları new , ve = bileşik atama işleçleri kullanan atamalar, artırma ve azaltma işlemlerini ve ++ -- işleçlerini ve await ifadelerini içerir.Expressions that can be used as statements include method invocations, object allocations using the new operator, assignments using = and the compound assignment operators, increment and decrement operations using the ++ and -- operators and await expressions.

Seçim deyimleri , bazı deyimlerin değerine göre yürütme için bir dizi olası deyimden birini seçmek için kullanılır.Selection statements are used to select one of a number of possible statements for execution based on the value of some expression. Bu grupta if ve switch deyimleri vardır.In this group are the if and switch statements.

Yineleme deyimleri , gömülü bir deyimi tekrar tekrar yürütmek için kullanılır.Iteration statements are used to repeatedly execute an embedded statement. Bu grupta while ,, do for ve foreach deyimleri bulunur.In this group are the while, do, for, and foreach statements.

Sıçrama deyimleri , denetimi aktarmak için kullanılır.Jump statements are used to transfer control. Bu grupta,,, break , continue goto throw return ve yield deyimleri bulunur.In this group are the break, continue, goto, throw, return, and yield statements.

try... catch Bildirisi, bir bloğun yürütülmesi sırasında oluşan özel durumları yakalamak için kullanılır ve try ... finally deyimleri her zaman yürütülen ve özel bir durumun gerçekleşmediği sonlandırma kodunu belirtmek için kullanılır.The try...catch statement is used to catch exceptions that occur during execution of a block, and the try...finally statement is used to specify finalization code that is always executed, whether an exception occurred or not.

checkedVe unchecked deyimleri, tamsayı türü aritmetik işlemler ve dönüştürmeler için taşma denetimi bağlamını denetlemek için kullanılır.The checked and unchecked statements are used to control the overflow checking context for integral-type arithmetic operations and conversions.

Bu lock ifade, belirli bir nesne için karşılıklı dışlama kilidini almak, bir ifadeyi yürütmek ve sonra kilidi serbest bırakmak için kullanılır.The lock statement is used to obtain the mutual-exclusion lock for a given object, execute a statement, and then release the lock.

usingİfade, kaynak almak, bir ifadeyi yürütmek ve ardından bu kaynağı atmak için kullanılır.The using statement is used to obtain a resource, execute a statement, and then dispose of that resource.

Aşağıda her bir tür deyimin örnekleri verilmiştirBelow are examples of each kind of statement

Yerel değişken bildirimleriLocal variable declarations

static void Main() {
   int a;
   int b = 2, c = 3;
   a = 1;
   Console.WriteLine(a + b + c);
}

Yerel sabit bildirimiLocal constant declaration

static void Main() {
    const float pi = 3.1415927f;
    const int r = 25;
    Console.WriteLine(pi * r * r);
}

İfade deyimiExpression statement

static void Main() {
    int i;
    i = 123;                // Expression statement
    Console.WriteLine(i);   // Expression statement
    i++;                    // Expression statement
    Console.WriteLine(i);   // Expression statement
}

if Ekstreif statement

static void Main(string[] args) {
    if (args.Length == 0) {
        Console.WriteLine("No arguments");
    }
    else {
        Console.WriteLine("One or more arguments");
    }
}

switch Ekstreswitch statement

static void Main(string[] args) {
    int n = args.Length;
    switch (n) {
        case 0:
            Console.WriteLine("No arguments");
            break;
        case 1:
            Console.WriteLine("One argument");
            break;
        default:
            Console.WriteLine("{0} arguments", n);
            break;
    }
}

while Ekstrewhile statement

static void Main(string[] args) {
    int i = 0;
    while (i < args.Length) {
        Console.WriteLine(args[i]);
        i++;
    }
}

do Ekstredo statement

static void Main() {
    string s;
    do {
        s = Console.ReadLine();
        if (s != null) Console.WriteLine(s);
    } while (s != null);
}

for Ekstrefor statement

static void Main(string[] args) {
    for (int i = 0; i < args.Length; i++) {
        Console.WriteLine(args[i]);
    }
}

foreach Ekstreforeach statement

static void Main(string[] args) {
    foreach (string s in args) {
        Console.WriteLine(s);
    }
}

break Ekstrebreak statement

static void Main() {
    while (true) {
        string s = Console.ReadLine();
        if (s == null) break;
        Console.WriteLine(s);
    }
}

continue Ekstrecontinue statement

static void Main(string[] args) {
    for (int i = 0; i < args.Length; i++) {
        if (args[i].StartsWith("/")) continue;
        Console.WriteLine(args[i]);
    }
}

goto Ekstregoto statement

static void Main(string[] args) {
    int i = 0;
    goto check;
    loop:
    Console.WriteLine(args[i++]);
    check:
    if (i < args.Length) goto loop;
}

return Ekstrereturn statement

static int Add(int a, int b) {
    return a + b;
}

static void Main() {
    Console.WriteLine(Add(1, 2));
    return;
}

yield Ekstreyield statement

static IEnumerable<int> Range(int from, int to) {
    for (int i = from; i < to; i++) {
        yield return i;
    }
    yield break;
}

static void Main() {
    foreach (int x in Range(-10,10)) {
        Console.WriteLine(x);
    }
}

throw ve try deyimlerithrow and try statements

static double Divide(double x, double y) {
    if (y == 0) throw new DivideByZeroException();
    return x / y;
}

static void Main(string[] args) {
    try {
        if (args.Length != 2) {
            throw new Exception("Two numbers required");
        }
        double x = double.Parse(args[0]);
        double y = double.Parse(args[1]);
        Console.WriteLine(Divide(x, y));
    }
    catch (Exception e) {
        Console.WriteLine(e.Message);
    }
    finally {
        Console.WriteLine("Good bye!");
    }
}

checked ve unchecked deyimlerichecked and unchecked statements

static void Main() {
    int i = int.MaxValue;
    checked {
        Console.WriteLine(i + 1);        // Exception
    }
    unchecked {
        Console.WriteLine(i + 1);        // Overflow
    }
}

lock Ekstrelock statement

class Account
{
    decimal balance;
    public void Withdraw(decimal amount) {
        lock (this) {
            if (amount > balance) {
                throw new Exception("Insufficient funds");
            }
            balance -= amount;
        }
    }
}

using Ekstreusing statement

static void Main() {
    using (TextWriter w = File.CreateText("test.txt")) {
        w.WriteLine("Line one");
        w.WriteLine("Line two");
        w.WriteLine("Line three");
    }
}

Sınıflar ve nesnelerClasses and objects

*Classes _, C# türlerinin en temel larıdır.*Classes _ are the most fundamental of C#'s types. Bir sınıf, durumu (alanları) ve eylemleri (Yöntemler ve diğer işlev üyelerini) tek bir birimde birleştiren bir veri yapısıdır.A class is a data structure that combines state (fields) and actions (methods and other function members) in a single unit. Sınıf, nesne olarak da bilinen, sınıfının dinamik olarak oluşturulan *örnekleri* için bir tanım sağlar.A class provides a definition for dynamically created instances of the class, also known as objects. Sınıflar Devralma ve çok biçimlilik destekler, türetilmiş sınıfların genişlettiği mekanizmalar _ temel sınıfları * öğesini genişletebilir ve özelleştirebilirsiniz.Classes support inheritance and polymorphism, mechanisms whereby derived classes can extend and specialize _*base classes**.

Yeni sınıflar sınıf bildirimleri kullanılarak oluşturulur.New classes are created using class declarations. Sınıf bildirimi, sınıfın özniteliklerini ve değiştiricilerini, sınıfın adını, Taban sınıfını (belirtilmişse) ve sınıf tarafından uygulanan arabirimleri belirten bir üstbilgiyle başlar.A class declaration starts with a header that specifies the attributes and modifiers of the class, the name of the class, the base class (if given), and the interfaces implemented by the class. Üst bilgi, sınırlayıcılar ve arasında yazılmış üye bildirimlerinin listesinden oluşan sınıf gövdesinden gelir { } .The header is followed by the class body, which consists of a list of member declarations written between the delimiters { and }.

Aşağıda adlı basit bir sınıfın bildirimi verilmiştir Point :The following is a declaration of a simple class named Point:

public class Point
{
    public int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Sınıf örnekleri new , yeni bir örnek için bellek ayıran işleç kullanılarak oluşturulur, örneği başlatmak için bir oluşturucu çağırır ve örneğe bir başvuru döndürür.Instances of classes are created using the new operator, which allocates memory for a new instance, invokes a constructor to initialize the instance, and returns a reference to the instance. Aşağıdaki deyimler iki nesne oluşturur Point ve bu nesnelere başvuruları iki değişken halinde depolar:The following statements create two Point objects and store references to those objects in two variables:

Point p1 = new Point(0, 0);
Point p2 = new Point(10, 20);

Nesne artık kullanımda olmadığında bir nesnenin kapladığı bellek otomatik olarak geri kazanılır.The memory occupied by an object is automatically reclaimed when the object is no longer in use. C# ' de nesneleri açıkça serbest bırakmak gerekli değildir veya mümkün değildir.It is neither necessary nor possible to explicitly deallocate objects in C#.

ÜyelerMembers

Bir sınıfın üyeleri *statik Üyeler _ veya _ örnek üyeleri *.The members of a class are either static members _ or _instance members**. Statik Üyeler sınıflara aittir ve örnek üyeleri nesnelere aittir (sınıf örnekleri).Static members belong to classes, and instance members belong to objects (instances of classes).

Aşağıdaki tabloda bir sınıfın içerebileceği üye türlerine genel bakış sunulmaktadır.The following table provides an overview of the kinds of members a class can contain.

ÜyeMember AçıklamaDescription
SabitlerConstants Sınıfla ilişkili sabit değerlerConstant values associated with the class
AlanlarFields Sınıfın değişkenleriVariables of the class
YöntemlerMethods Sınıfı tarafından gerçekleştirilebilecek hesaplamalar ve eylemlerComputations and actions that can be performed by the class
ÖzelliklerProperties Sınıfın adlandırılmış özelliklerini okuma ve yazma ile ilişkili eylemlerActions associated with reading and writing named properties of the class
Dizin OluşturucularIndexers Bir dizi gibi sınıfın dizin oluşturma örnekleri ile ilişkili eylemlerActions associated with indexing instances of the class like an array
EkinliklerEvents Sınıfı tarafından oluşturulabilecek bildirimlerNotifications that can be generated by the class
İşleçlerOperators Sınıf tarafından desteklenen dönüşümler ve ifade işleçleriConversions and expression operators supported by the class
OluşturucularConstructors Sınıfın veya sınıfın örneklerinin örneğini başlatmak için gereken eylemlerActions required to initialize instances of the class or the class itself
YıkıcılarDestructors Sınıfın örneklerinden önce gerçekleştirilecek eylemler kalıcı olarak atılırActions to perform before instances of the class are permanently discarded
TürlerTypes Sınıf tarafından tanımlanan iç içe türlerNested types declared by the class

ErişilebilirlikAccessibility

Bir sınıfın her üyesinin ilişkili bir erişilebilirliği vardır ve bu, üyeye erişebilen program metni bölgelerini denetler.Each member of a class has an associated accessibility, which controls the regions of program text that are able to access the member. Olası beş erişilebilirlik biçimi vardır.There are five possible forms of accessibility. Bunlar aşağıdaki tabloda özetlenmiştir.These are summarized in the following table.

ErişilebilirlikAccessibility AnlamıMeaning
public Erişim sınırlı değilAccess not limited
protected Bu sınıftan türetilmiş bu sınıfla veya sınıflarla sınırlı erişimAccess limited to this class or classes derived from this class
internal Bu programla sınırlı erişimAccess limited to this program
protected internal Bu sınıftan türetilmiş bu program veya sınıflarla sınırlı erişimAccess limited to this program or classes derived from this class
private Bu sınıfla sınırlı erişimAccess limited to this class

Tür parametreleriType parameters

Sınıf tanımı, tür parametre adlarının bir listesini kapsayan açılı ayraçları olan sınıf adını izleyerek bir tür parametreleri kümesi belirtebilir.A class definition may specify a set of type parameters by following the class name with angle brackets enclosing a list of type parameter names. Daha sonra tür parametreleri sınıfının üyelerini tanımlamak için sınıf bildirimlerinin gövdesinde kullanılabilir.The type parameters can then be used in the body of the class declarations to define the members of the class. Aşağıdaki örnekte, öğesinin tür parametreleri Pair TFirst ve TSecond :In the following example, the type parameters of Pair are TFirst and TSecond:

public class Pair<TFirst,TSecond>
{
    public TFirst First;
    public TSecond Second;
}

Tür parametrelerini almak için belirtilen bir sınıf türüne genel sınıf türü denir.A class type that is declared to take type parameters is called a generic class type. Yapı, arabirim ve temsilci türleri de genel olabilir.Struct, interface and delegate types can also be generic.

Genel sınıf kullanıldığında, tür parametrelerinin her biri için tür bağımsız değişkenlerinin sağlanması gerekir:When the generic class is used, type arguments must be provided for each of the type parameters:

Pair<int,string> pair = new Pair<int,string> { First = 1, Second = "two" };
int i = pair.First;     // TFirst is int
string s = pair.Second; // TSecond is string

Yukarıda olduğu gibi, tür bağımsız değişkenlerine sahip genel bir tür, Pair<int,string> oluşturulmuş bir tür olarak adlandırılır.A generic type with type arguments provided, like Pair<int,string> above, is called a constructed type.

Temel sınıflarBase classes

Sınıf bildirimi, sınıf adı ve tür parametreleri iki nokta ve temel sınıfın adı ile birlikte bir temel sınıf belirtebilir.A class declaration may specify a base class by following the class name and type parameters with a colon and the name of the base class. Temel sınıf belirtiminin atlanması, türden türetmeye benzer object .Omitting a base class specification is the same as deriving from type object. Aşağıdaki örnekte, öğesinin temel sınıfı Point3D Point ve öğesinin temel sınıfı Point object :In the following example, the base class of Point3D is Point, and the base class of Point is object:

public class Point
{
    public int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

public class Point3D: Point
{
    public int z;

    public Point3D(int x, int y, int z): base(x, y) {
        this.z = z;
    }
}

Bir sınıf, temel sınıfının üyelerini devralır.A class inherits the members of its base class. Devralma, bir sınıfın örnek ve statik oluşturucular ve temel sınıfın yıkıcıları dışında, temel sınıfının tüm üyelerini örtük olarak içerdiği anlamına gelir.Inheritance means that a class implicitly contains all members of its base class, except for the instance and static constructors, and the destructors of the base class. Türetilmiş bir sınıf, devralananlara yeni üyeler ekleyebilir, ancak devralınmış bir üyenin tanımını kaldıramaz.A derived class can add new members to those it inherits, but it cannot remove the definition of an inherited member. Önceki örnekte, Point3D x ve y alanlarını öğesinden devralır Point ve her Point3D örnek üç alan içerir,, x y ve z .In the previous example, Point3D inherits the x and y fields from Point, and every Point3D instance contains three fields, x, y, and z.

Bir sınıf türünden, temel sınıf türlerinden herhangi birine örtük bir dönüştürme vardır.An implicit conversion exists from a class type to any of its base class types. Bu nedenle, bir sınıf türünün değişkeni bu sınıfın bir örneğine veya türetilmiş herhangi bir sınıfın örneğine başvurabilir.Therefore, a variable of a class type can reference an instance of that class or an instance of any derived class. Örneğin, önceki sınıf bildirimleri verildiğinde, türünde bir değişken Point bir Point veya a başvurabilir Point3D :For example, given the previous class declarations, a variable of type Point can reference either a Point or a Point3D:

Point a = new Point(10, 20);
Point b = new Point3D(10, 20, 30);

AlanlarFields

Alan, bir sınıf ile veya bir sınıf örneğiyle ilişkili bir değişkendir.A field is a variable that is associated with a class or with an instance of a class.

Değiştiriciyle belirtilen bir alan static statik bir alan tanımlar.A field declared with the static modifier defines a static field. Statik alan tam olarak bir depolama konumunu tanımlar.A static field identifies exactly one storage location. Bir sınıfın kaç örneğinin oluşturulduğuna bakılmaksızın, bir statik alanın yalnızca bir kopyası vardır.No matter how many instances of a class are created, there is only ever one copy of a static field.

Değiştirici olmadan belirtilen bir alan bir static örnek alanını tanımlar.A field declared without the static modifier defines an instance field. Bir sınıfın her örneği, bu sınıfın tüm örnek alanlarının ayrı bir kopyasını içerir.Every instance of a class contains a separate copy of all the instance fields of that class.

Aşağıdaki örnekte, sınıfının her örneği Color ,, ve örnek alanlarının ayrı bir kopyasına sahiptir ancak,,,, r g b Black White Red Green ve Blue statik alanlarının yalnızca bir kopyası vardır:In the following example, each instance of the Color class has a separate copy of the r, g, and b instance fields, but there is only one copy of the Black, White, Red, Green, and Blue static fields:

public class Color
{
    public static readonly Color Black = new Color(0, 0, 0);
    public static readonly Color White = new Color(255, 255, 255);
    public static readonly Color Red = new Color(255, 0, 0);
    public static readonly Color Green = new Color(0, 255, 0);
    public static readonly Color Blue = new Color(0, 0, 255);
    private byte r, g, b;

    public Color(byte r, byte g, byte b) {
        this.r = r;
        this.g = g;
        this.b = b;
    }
}

Önceki örnekte gösterildiği gibi, salt okuma alanları bir değiştirici ile bildirilebilecek readonly .As shown in the previous example, read-only fields may be declared with a readonly modifier. Bir alana atama readonly yalnızca alanın bildiriminin veya aynı sınıftaki bir oluşturucunun parçası olarak gerçekleşebilir.Assignment to a readonly field can only occur as part of the field's declaration or in a constructor in the same class.

YöntemlerMethods

*Yöntemi _ bir nesne veya sınıf tarafından gerçekleştirilebilecek bir hesaplama veya eylem uygulayan bir üyedir.A *method _ is a member that implements a computation or action that can be performed by an object or class. Statik yöntemlere sınıfı aracılığıyla erişilir.Static methods are accessed through the class. _ *Instance yöntemlerine**, sınıfının örnekleri aracılığıyla erişilir._ Instance methods* are accessed through instances of the class.

Yöntemler, yöntemine geçirilen değerleri veya değişken başvurularını temsil eden *Parameters _ (muhtemelen boş) listesine sahiptir ve bir _ dönüş türü *, hesaplanan ve yöntemi tarafından döndürülen değerin türünü belirtir.Methods have a (possibly empty) list of parameters _, which represent values or variable references passed to the method, and a _return type**, which specifies the type of the value computed and returned by the method. Bir yöntemin dönüş türü void bir değer döndürmezse.A method's return type is void if it does not return a value.

Türler gibi yöntemler de bir tür parametreleri kümesine sahip olabilir, bu da yöntem çağrıldığında tür bağımsız değişkenlerinin belirtilmesi gerekir.Like types, methods may also have a set of type parameters, for which type arguments must be specified when the method is called. Türlerin aksine, tür bağımsız değişkenleri genellikle yöntem çağrısının bağımsız değişkenlerinden çıkarsanamıyor ve açıkça verilmemelidir.Unlike types, the type arguments can often be inferred from the arguments of a method call and need not be explicitly given.

Yöntemin imzası , yöntemin bildirildiği sınıfta benzersiz olmalıdır.The signature of a method must be unique in the class in which the method is declared. Bir yöntemin imzası yöntemin adından, tür parametrelerinin sayısına ve parametrelerinin sayısına, değiştiricilerine ve türlerine sahiptir.The signature of a method consists of the name of the method, the number of type parameters and the number, modifiers, and types of its parameters. Bir yöntemin imzası, dönüş türünü içermez.The signature of a method does not include the return type.

ParametrelerParameters

Parametreler, değerlere veya değişken başvurularını yöntemlere geçirmek için kullanılır.Parameters are used to pass values or variable references to methods. Bir yöntemin parametreleri, yöntemi çağrıldığında belirtilen bağımsız değişkenlerden gerçek değerlerini alır.The parameters of a method get their actual values from the arguments that are specified when the method is invoked. Dört tür parametre vardır: değer parametreleri, başvuru parametreleri, çıkış parametreleri ve parametre dizileri.There are four kinds of parameters: value parameters, reference parameters, output parameters, and parameter arrays.

Giriş parametresi geçirme için bir değer parametresi kullanılır.A value parameter is used for input parameter passing. Değer parametresi, parametresi için geçirilen bağımsız değişkenden ilk değerini alan yerel bir değişkene karşılık gelir.A value parameter corresponds to a local variable that gets its initial value from the argument that was passed for the parameter. Değer parametresindeki değişiklikler, parametresi için geçirilen bağımsız değişkeni etkilemez.Modifications to a value parameter do not affect the argument that was passed for the parameter.

Değer parametreleri, ilgili bağımsız değişkenlerin atlanabilmesi için varsayılan bir değer belirtilerek isteğe bağlı olabilir.Value parameters can be optional, by specifying a default value so that corresponding arguments can be omitted.

Hem giriş hem de çıkış parametresi geçirme için başvuru parametresi kullanılır.A reference parameter is used for both input and output parameter passing. Başvuru parametresi için geçirilen bağımsız değişken bir değişken olmalıdır ve yöntemin yürütülmesi sırasında başvuru parametresi, bağımsız değişken değişkeniyle aynı depolama konumunu temsil eder.The argument passed for a reference parameter must be a variable, and during execution of the method, the reference parameter represents the same storage location as the argument variable. Bir başvuru parametresi değiştiriciyle birlikte bildirilmiştir ref .A reference parameter is declared with the ref modifier. Aşağıdaki örnek parametrelerin kullanımını gösterir ref .The following example shows the use of ref parameters.

using System;

class Test
{
    static void Swap(ref int x, ref int y) {
        int temp = x;
        x = y;
        y = temp;
    }

    static void Main() {
        int i = 1, j = 2;
        Swap(ref i, ref j);
        Console.WriteLine("{0} {1}", i, j);            // Outputs "2 1"
    }
}

Çıkış parametresi geçirme için çıkış parametresi kullanılır.An output parameter is used for output parameter passing. Bir çıktı parametresi, çağıran tarafından belirtilen bağımsız değişkenin ilk değeri önemli olmayan bir başvuru parametresine benzerdir.An output parameter is similar to a reference parameter except that the initial value of the caller-provided argument is unimportant. Bir çıkış parametresi değiştiriciyle birlikte bildirilmiştir out .An output parameter is declared with the out modifier. Aşağıdaki örnek parametrelerin kullanımını gösterir out .The following example shows the use of out parameters.

using System;

class Test
{
    static void Divide(int x, int y, out int result, out int remainder) {
        result = x / y;
        remainder = x % y;
    }

    static void Main() {
        int res, rem;
        Divide(10, 3, out res, out rem);
        Console.WriteLine("{0} {1}", res, rem);    // Outputs "3 1"
    }
}

Bir parametre dizisi , bir metoda değişken sayıda bağımsız değişken geçirilmesine izin verir.A parameter array permits a variable number of arguments to be passed to a method. Bir parametre dizisi değiştiriciyle birlikte bildirilmiştir params .A parameter array is declared with the params modifier. Bir yöntemin yalnızca son parametresi bir parametre dizisi olabilir ve bir parametre dizisinin türü tek boyutlu bir dizi türü olmalıdır.Only the last parameter of a method can be a parameter array, and the type of a parameter array must be a single-dimensional array type. WriteSınıfının ve WriteLine yöntemleri, System.Console parametre dizisi kullanımının iyi örnekleridir.The Write and WriteLine methods of the System.Console class are good examples of parameter array usage. Bunlar aşağıdaki gibi bildirilmiştir.They are declared as follows.

public class Console
{
    public static void Write(string fmt, params object[] args) {...}
    public static void WriteLine(string fmt, params object[] args) {...}
    ...
}

Bir parametre dizisi kullanan bir yöntem içinde, parametre dizisi tam olarak bir dizi türünün normal parametresine benzer şekilde davranır.Within a method that uses a parameter array, the parameter array behaves exactly like a regular parameter of an array type. Ancak, bir parametre dizisi olan bir yöntem çağrısında, parametre dizisi türünün tek bir bağımsız değişkenini veya parametre dizisinin öğe türünün herhangi bir sayıda bağımsız değişkenini geçirmek mümkündür.However, in an invocation of a method with a parameter array, it is possible to pass either a single argument of the parameter array type or any number of arguments of the element type of the parameter array. İkinci durumda, bir dizi örneği otomatik olarak oluşturulur ve verilen bağımsız değişkenlerle başlatılır.In the latter case, an array instance is automatically created and initialized with the given arguments. Bu örnekThis example

Console.WriteLine("x={0} y={1} z={2}", x, y, z);

, aşağıdaki yazma ile eşdeğerdir.is equivalent to writing the following.

string s = "x={0} y={1} z={2}";
object[] args = new object[3];
args[0] = x;
args[1] = y;
args[2] = z;
Console.WriteLine(s, args);

Yöntem gövdesi ve yerel değişkenlerMethod body and local variables

Yöntemin gövdesi, yöntemi çağrıldığında yürütülecek deyimleri belirtir.A method's body specifies the statements to execute when the method is invoked.

Yöntem gövdesi, yöntemi çağrısına özgü değişkenleri bildirebilir.A method body can declare variables that are specific to the invocation of the method. Bu tür değişkenlere yerel değişkenler denir.Such variables are called local variables. Yerel bir değişken bildirimi bir tür adı, değişken adı ve muhtemelen bir başlangıç değeri belirtir.A local variable declaration specifies a type name, a variable name, and possibly an initial value. Aşağıdaki örnek, başlangıç değeri sıfır olan yerel bir değişken i ve ilk değeri olmayan bir yerel değişken bildirir j .The following example declares a local variable i with an initial value of zero and a local variable j with no initial value.

using System;

class Squares
{
    static void Main() {
        int i = 0;
        int j;
        while (i < 10) {
            j = i * i;
            Console.WriteLine("{0} x {0} = {1}", i, j);
            i = i + 1;
        }
    }
}

C# değeri alınabilmesi için önce bir yerel değişkenin kesinlikle atanmasını gerektirir.C# requires a local variable to be definitely assigned before its value can be obtained. Örneğin, önceki bildiriminde i bir başlangıç değeri yoksa, derleyici programın sonraki kullanımları için bir hata bildirir i çünkü i Bu, programda bu noktalarda kesinlikle atanmamalıdır.For example, if the declaration of the previous i did not include an initial value, the compiler would report an error for the subsequent usages of i because i would not be definitely assigned at those points in the program.

Bir yöntem return , çağrı yapana denetim döndürmek için deyimlerini kullanabilir.A method can use return statements to return control to its caller. Döndürülen bir yöntemde void return deyimler bir ifade belirtemez.In a method returning void, return statements cannot specify an expression. Olmayan deyimler döndüren bir yöntemde void , return dönüş değerini hesaplayan bir ifade içermelidir.In a method returning non-void, return statements must include an expression that computes the return value.

Statik ve örnek yöntemleriStatic and instance methods

Değiştirici ile belirtilen bir yöntem static statik bir yöntemdir.A method declared with a static modifier is a static method. Statik bir yöntem belirli bir örnek üzerinde çalışmaz ve yalnızca statik üyelere doğrudan erişebilir.A static method does not operate on a specific instance and can only directly access static members.

Değiştirici olmadan bildirildiği bir yöntem static bir örnek yöntemidir.A method declared without a static modifier is an instance method. Örnek yöntemi, belirli bir örnek üzerinde çalışır ve hem statik hem de örnek üyelerine erişebilir.An instance method operates on a specific instance and can access both static and instance members. Örnek yönteminin çağrıldığı örnek, olarak açıkça erişilebilir this .The instance on which an instance method was invoked can be explicitly accessed as this. Statik bir yöntemde başvurmak için bir hatadır this .It is an error to refer to this in a static method.

Aşağıdaki Entity sınıfta hem statik hem de örnek üyeleri vardır.The following Entity class has both static and instance members.

class Entity
{
    static int nextSerialNo;
    int serialNo;

    public Entity() {
        serialNo = nextSerialNo++;
    }

    public int GetSerialNo() {
        return serialNo;
    }

    public static int GetNextSerialNo() {
        return nextSerialNo;
    }

    public static void SetNextSerialNo(int value) {
        nextSerialNo = value;
    }
}

Her Entity örnek bir seri numarası içerir (ve burada görünmeyen bazı diğer bilgileri kabul etmez).Each Entity instance contains a serial number (and presumably some other information that is not shown here). EntityOluşturucu (bir örnek yöntemi gibi) yeni örneği bir sonraki kullanılabilir seri numarasıyla başlatır.The Entity constructor (which is like an instance method) initializes the new instance with the next available serial number. Oluşturucu bir örnek üyesi olduğundan, hem serialNo örnek alanına hem de statik alana erişim izni verilir nextSerialNo .Because the constructor is an instance member, it is permitted to access both the serialNo instance field and the nextSerialNo static field.

GetNextSerialNoVe SetNextSerialNo statik yöntemler nextSerialNo statik alana erişebilir, ancak örnek alanına doğrudan erişmesi için bir hata olabilir serialNo .The GetNextSerialNo and SetNextSerialNo static methods can access the nextSerialNo static field, but it would be an error for them to directly access the serialNo instance field.

Aşağıdaki örnek sınıfının kullanımını gösterir Entity .The following example shows the use of the Entity class.

using System;

class Test
{
    static void Main() {
        Entity.SetNextSerialNo(1000);
        Entity e1 = new Entity();
        Entity e2 = new Entity();
        Console.WriteLine(e1.GetSerialNo());           // Outputs "1000"
        Console.WriteLine(e2.GetSerialNo());           // Outputs "1001"
        Console.WriteLine(Entity.GetNextSerialNo());   // Outputs "1002"
    }
}

Sınıfının SetNextSerialNo GetNextSerialNo GetSerialNo örneklerinde örnek yöntemi çağrıldığında, ve statik yöntemlerin sınıfında çağrılabileceğini unutmayın.Note that the SetNextSerialNo and GetNextSerialNo static methods are invoked on the class whereas the GetSerialNo instance method is invoked on instances of the class.

Sanal, geçersiz kılma ve soyut yöntemlerVirtual, override, and abstract methods

Bir örnek yöntemi bildirimi bir değiştirici içerdiğinde virtual , yöntemi *sanal yöntemi _ olarak kabul edilir.When an instance method declaration includes a virtual modifier, the method is said to be a *virtual method _. Değiştirici yoksa virtual , yöntemi _ sanal olmayan * yöntemi olarak kabul edilir.When no virtual modifier is present, the method is said to be a _*non-virtual method**.

Sanal bir yöntem çağrıldığında, çağrının gerçekleştiği örneğin *çalışma zamanı türü _, çağrılacak gerçek Yöntem uygulamasını belirler.When a virtual method is invoked, the *run-time type _ of the instance for which that invocation takes place determines the actual method implementation to invoke. Sanal olmayan bir yöntem çağrısında, örneğin _ *derleme zamanı türü**, belirleme faktördür.In a nonvirtual method invocation, the _ compile-time type* of the instance is the determining factor.

Bir sanal yöntem, türetilmiş bir sınıfta geçersiz kılınabilir .A virtual method can be overridden in a derived class. Bir örnek yöntemi bildirimi bir değiştirici içerdiğinde override , yöntemi aynı imzaya sahip devralınmış bir sanal yöntemi geçersiz kılar.When an instance method declaration includes an override modifier, the method overrides an inherited virtual method with the same signature. Sanal bir yöntem bildiriminde yeni bir yöntem tanıtıldığı halde, bir geçersiz kılma yöntemi bildirimi, bu yöntemin yeni bir uygulamasını sağlayarak, var olan bir devralınmış sanal yöntemi uzmanlık eder.Whereas a virtual method declaration introduces a new method, an override method declaration specializes an existing inherited virtual method by providing a new implementation of that method.

Soyut bir yöntem, uygulama içermeyen bir sanal yöntemdir.An abstract method is a virtual method with no implementation. Soyut bir yöntem değiştiriciyle birlikte bildirilmiştir abstract ve yalnızca da belirtilen bir sınıfta izin verilir abstract .An abstract method is declared with the abstract modifier and is permitted only in a class that is also declared abstract. Soyut olmayan her türetilmiş sınıfta bir soyut yöntem geçersiz kılınmalıdır.An abstract method must be overridden in every non-abstract derived class.

Aşağıdaki örnek, Expression bir ifade ağaç düğümünü temsil eden bir soyut sınıfı ve Constant VariableReference Operation sabitler, değişken başvuruları ve aritmetik işlemler için ifade ağacı düğümleri uygulayan üç türetilmiş sınıfı,, ve ' ı tanımlar.The following example declares an abstract class, Expression, which represents an expression tree node, and three derived classes, Constant, VariableReference, and Operation, which implement expression tree nodes for constants, variable references, and arithmetic operations. (Bu şuna benzerdir, ancak ifade ağacı türlerindetanıtılan ifade ağacı türleriyle karıştırılmamalıdır).(This is similar to, but not to be confused with the expression tree types introduced in Expression tree types).

using System;
using System.Collections;

public abstract class Expression
{
    public abstract double Evaluate(Hashtable vars);
}

public class Constant: Expression
{
    double value;

    public Constant(double value) {
        this.value = value;
    }

    public override double Evaluate(Hashtable vars) {
        return value;
    }
}

public class VariableReference: Expression
{
    string name;

    public VariableReference(string name) {
        this.name = name;
    }

    public override double Evaluate(Hashtable vars) {
        object value = vars[name];
        if (value == null) {
            throw new Exception("Unknown variable: " + name);
        }
        return Convert.ToDouble(value);
    }
}

public class Operation: Expression
{
    Expression left;
    char op;
    Expression right;

    public Operation(Expression left, char op, Expression right) {
        this.left = left;
        this.op = op;
        this.right = right;
    }

    public override double Evaluate(Hashtable vars) {
        double x = left.Evaluate(vars);
        double y = right.Evaluate(vars);
        switch (op) {
            case '+': return x + y;
            case '-': return x - y;
            case '*': return x * y;
            case '/': return x / y;
        }
        throw new Exception("Unknown operator");
    }
}

Önceki dört sınıf aritmetik ifadeleri modellemek için kullanılabilir.The previous four classes can be used to model arithmetic expressions. Örneğin, bu sınıfların örneklerini kullanarak, ifadesi x + 3 aşağıdaki gibi gösterilebilir.For example, using instances of these classes, the expression x + 3 can be represented as follows.

Expression e = new Operation(
    new VariableReference("x"),
    '+',
    new Constant(3));

EvaluateBir örneğin yöntemi, Expression verilen ifadeyi değerlendirmek ve bir değer üretmek için çağrılır double .The Evaluate method of an Expression instance is invoked to evaluate the given expression and produce a double value. Yöntemi, Hashtable değişken adlarını (girdilerin anahtarları olarak) ve değerlerini (girdilerin değerleri olarak) içeren bir bağımsız değişken olarak alır.The method takes as an argument a Hashtable that contains variable names (as keys of the entries) and values (as values of the entries). EvaluateYöntemi, bir sanal soyut yöntemidir, yani soyut olmayan türetilmiş sınıfların gerçek bir uygulama sağlamak için onu geçersiz kılması gerekir.The Evaluate method is a virtual abstract method, meaning that non-abstract derived classes must override it to provide an actual implementation.

' Constant Nin uygulanması, Evaluate yalnızca saklı sabiti döndürür.A Constant's implementation of Evaluate simply returns the stored constant. Bir VariableReference uygulama, Hashtable 'daki değişken adını arar ve elde edilen değeri döndürür.A VariableReference's implementation looks up the variable name in the hashtable and returns the resulting value. Bir Operation uygulama ilk olarak sol ve sağ işlenenleri değerlendirir (yöntemlerini özyinelemeli olarak çağırarak Evaluate ) ve ardından verilen aritmetik işlemi gerçekleştirir.An Operation's implementation first evaluates the left and right operands (by recursively invoking their Evaluate methods) and then performs the given arithmetic operation.

Aşağıdaki program, Expression x * (y + 2) ve farklı değerleri için ifadeyi değerlendirmek için sınıflarını kullanır x y .The following program uses the Expression classes to evaluate the expression x * (y + 2) for different values of x and y.

using System;
using System.Collections;

class Test
{
    static void Main() {
        Expression e = new Operation(
            new VariableReference("x"),
            '*',
            new Operation(
                new VariableReference("y"),
                '+',
                new Constant(2)
            )
        );
        Hashtable vars = new Hashtable();
        vars["x"] = 3;
        vars["y"] = 5;
        Console.WriteLine(e.Evaluate(vars));        // Outputs "21"
        vars["x"] = 1.5;
        vars["y"] = 9;
        Console.WriteLine(e.Evaluate(vars));        // Outputs "16.5"
    }
}

Yöntem aşırı yüklemesiMethod overloading

*Aþýrý yükleme _ yöntemi, aynı sınıftaki birden çok metodun benzersiz imzalara sahip oldukları sürece aynı ada sahip olmasını sağlar.Method *overloading _ permits multiple methods in the same class to have the same name as long as they have unique signatures. Aşırı yüklenmiş bir yöntemin çağrılması derlenirken, derleyici, çağrılacak özel yöntemi öğrenmek için _ aşırı yükleme çözümü* kullanır.When compiling an invocation of an overloaded method, the compiler uses _ overload resolution* to determine the specific method to invoke. Aşırı yükleme çözümlemesi, bağımsız değişkenlerle en iyi eşleşen bir yöntemi bulur veya tek bir en iyi eşleşme bulunamazsa hata bildiriyor.Overload resolution finds the one method that best matches the arguments or reports an error if no single best match can be found. Aşağıdaki örnekte, etkin olan aşırı yükleme çözümü gösterilmektedir.The following example shows overload resolution in effect. Yöntemi içindeki her çağrının yorumu Main aslında hangi yöntemin çağrılacağını gösterir.The comment for each invocation in the Main method shows which method is actually invoked.

class Test
{
    static void F() {
        Console.WriteLine("F()");
    }

    static void F(object x) {
        Console.WriteLine("F(object)");
    }

    static void F(int x) {
        Console.WriteLine("F(int)");
    }

    static void F(double x) {
        Console.WriteLine("F(double)");
    }

    static void F<T>(T x) {
        Console.WriteLine("F<T>(T)");
    }

    static void F(double x, double y) {
        Console.WriteLine("F(double, double)");
    }

    static void Main() {
        F();                 // Invokes F()
        F(1);                // Invokes F(int)
        F(1.0);              // Invokes F(double)
        F("abc");            // Invokes F(object)
        F((double)1);        // Invokes F(double)
        F((object)1);        // Invokes F(object)
        F<int>(1);           // Invokes F<T>(T)
        F(1, 1);             // Invokes F(double, double)
    }
}

Örnekte gösterildiği gibi belirli bir yöntem her zaman bağımsız değişkenleri tam parametre türlerine açıkça atayarak ve/veya açıkça tür bağımsız değişkenleri sunarak seçilebilir.As shown by the example, a particular method can always be selected by explicitly casting the arguments to the exact parameter types and/or explicitly supplying type arguments.

Diğer işlev üyeleriOther function members

Yürütülebilir kod içeren Üyeler topluca bir sınıfın işlev üyeleri olarak bilinir.Members that contain executable code are collectively known as the function members of a class. Yukarıdaki bölümde, işlev üyelerinin birincil türü olan yöntemler açıklanmıştır.The preceding section describes methods, which are the primary kind of function members. Bu bölümde C# tarafından desteklenen diğer işlev üyesi türleri açıklanmaktadır: oluşturucular, özellikler, Dizin oluşturucular, olaylar, işleçler ve Yıkıcılar.This section describes the other kinds of function members supported by C#: constructors, properties, indexers, events, operators, and destructors.

Aşağıdaki kod List<T> , bir nesne growable listesini uygulayan adlı bir genel sınıfı gösterir.The following code shows a generic class called List<T>, which implements a growable list of objects. Sınıfı, en yaygın işlev üyesi türlerine birkaç örnek içerir.The class contains several examples of the most common kinds of function members.

public class List<T> {
    // Constant...
    const int defaultCapacity = 4;

    // Fields...
    T[] items;
    int count;

    // Constructors...
    public List(int capacity = defaultCapacity) {
        items = new T[capacity];
    }

    // Properties...
    public int Count {
        get { return count; }
    }
    public int Capacity {
        get {
            return items.Length;
        }
        set {
            if (value < count) value = count;
            if (value != items.Length) {
                T[] newItems = new T[value];
                Array.Copy(items, 0, newItems, 0, count);
                items = newItems;
            }
        }
    }

    // Indexer...
    public T this[int index] {
        get {
            return items[index];
        }
        set {
            items[index] = value;
            OnChanged();
        }
    }

    // Methods...
    public void Add(T item) {
        if (count == Capacity) Capacity = count * 2;
        items[count] = item;
        count++;
        OnChanged();
    }
    protected virtual void OnChanged() {
        if (Changed != null) Changed(this, EventArgs.Empty);
    }
    public override bool Equals(object other) {
        return Equals(this, other as List<T>);
    }
    static bool Equals(List<T> a, List<T> b) {
        if (a == null) return b == null;
        if (b == null || a.count != b.count) return false;
        for (int i = 0; i < a.count; i++) {
            if (!object.Equals(a.items[i], b.items[i])) {
                return false;
            }
        }
        return true;
    }

    // Event...
    public event EventHandler Changed;

    // Operators...
    public static bool operator ==(List<T> a, List<T> b) {
        return Equals(a, b);
    }
    public static bool operator !=(List<T> a, List<T> b) {
        return !Equals(a, b);
    }
}

OluşturucularConstructors

C# hem örnek hem de statik oluşturucuları destekler.C# supports both instance and static constructors. *Örnek Oluşturucusu , bir sınıfın örneğini başlatmak için gereken eylemleri uygulayan bir üyesidir.An *instance constructor _ is a member that implements the actions required to initialize an instance of a class. *Statik Oluşturucusu**, ilk yüklendiği zaman bir sınıfın kendisini başlatmak için gereken eylemleri uygulayan bir üyesidir.A _ static constructor* is a member that implements the actions required to initialize a class itself when it is first loaded.

Bir Oluşturucu, dönüş türü olmayan bir yöntem ve kapsayan sınıfla aynı adı ile birlikte bildirilmiştir.A constructor is declared like a method with no return type and the same name as the containing class. Bir Oluşturucu bildiriminde bir değiştirici varsa static , bir statik oluşturucu bildirir.If a constructor declaration includes a static modifier, it declares a static constructor. Aksi takdirde, bir örnek Oluşturucu bildirir.Otherwise, it declares an instance constructor.

Örnek oluşturucular aşırı yüklenebilir.Instance constructors can be overloaded. Örneğin, List<T> sınıfı, biri parametresi olmayan iki örnek Oluşturucu bildirir ve bir int parametre alır.For example, the List<T> class declares two instance constructors, one with no parameters and one that takes an int parameter. Örnek oluşturucular işleci kullanılarak çağrılır new .Instance constructors are invoked using the new operator. Aşağıdaki deyimler, List<string> sınıfının oluşturucularının her birini kullanarak iki örnek ayırır List .The following statements allocate two List<string> instances using each of the constructors of the List class.

List<string> list1 = new List<string>();
List<string> list2 = new List<string>(10);

Diğer üyelerin aksine, örnek oluşturucular devralınmaz ve bir sınıfın sınıfta tanımlananlardan farklı örnek oluşturucuları yoktur.Unlike other members, instance constructors are not inherited, and a class has no instance constructors other than those actually declared in the class. Bir sınıf için örnek Oluşturucu sağlanmazsa, parametresi olmayan boş bir değer otomatik olarak sağlanır.If no instance constructor is supplied for a class, then an empty one with no parameters is automatically provided.

ÖzelliklerProperties

*Properties _, alanların doğal bir uzantısıdır.*Properties _ are a natural extension of fields. Her ikisi de ilişkili türlerin bulunduğu isimlerdir ve alanlara ve özelliklere erişim için sözdizimi aynıdır.Both are named members with associated types, and the syntax for accessing fields and properties is the same. Ancak, alanların aksine, Özellikler depolama konumlarını göstermiyor.However, unlike fields, properties do not denote storage locations. Bunun yerine, özelliklerde, değerleri okunmadığında veya yazıldığında yürütülecek deyimleri belirten _ erişimcileri* vardır.Instead, properties have _ accessors* that specify the statements to be executed when their values are read or written.

Bir özellik, bildirim bir erişimci ile sona erene get ve/veya set sınırlayıcılar arasında yazılmış bir erişimciyi ve { noktalı virgül ile sona } ermek yerine bir alan olarak belirtilir.A property is declared like a field, except that the declaration ends with a get accessor and/or a set accessor written between the delimiters { and } instead of ending in a semicolon. Hem erişimci hem de erişimciye sahip olan bir özellik, get set okuma-yazma özelliği _, yalnızca bir erişimciye sahip olan bir özellik get _salt okunurdur*_ ve yalnızca bir erişimcisi olan bir özellik set _ * salt yazılır bir özelliktir * *.A property that has both a get accessor and a set accessor is a read-write property _, a property that has only a get accessor is a _read-only property_, and a property that has only a set accessor is a _write-only property**.

getErişimci, özellik türünün dönüş değeri olan parametresiz bir yönteme karşılık gelir.A get accessor corresponds to a parameterless method with a return value of the property type. Atama hedefi dışında, bir ifadede bir özelliğe başvurulduğunda, özelliğin get erişimcisi özelliğin değerini hesaplamak için çağrılır.Except as the target of an assignment, when a property is referenced in an expression, the get accessor of the property is invoked to compute the value of the property.

setErişimci value , adlandırılmış ve dönüş türü olmayan tek parametreli bir yönteme karşılık gelir.A set accessor corresponds to a method with a single parameter named value and no return type. Bir özelliğe bir atamanın hedefi veya işleneni olarak başvurulduğunda ++ -- , set erişimci yeni değeri sağlayan bir bağımsız değişkenle çağrılır.When a property is referenced as the target of an assignment or as the operand of ++ or --, the set accessor is invoked with an argument that provides the new value.

List<T>Sınıfı iki özellik bildirir Count ve Capacity sırasıyla salt okunurdur ve okuma-yazma olur.The List<T> class declares two properties, Count and Capacity, which are read-only and read-write, respectively. Aşağıda bu özelliklerin kullanılmasına bir örnek verilmiştir.The following is an example of use of these properties.

List<string> names = new List<string>();
names.Capacity = 100;            // Invokes set accessor
int i = names.Count;             // Invokes get accessor
int j = names.Capacity;          // Invokes get accessor

Alanlar ve yöntemlere benzer şekilde C# hem örnek özelliklerini hem de statik özellikleri destekler.Similar to fields and methods, C# supports both instance properties and static properties. Statik özellikler static değiştiriciyle, örnek özellikleri ise bu olmadan tanımlanır.Static properties are declared with the static modifier, and instance properties are declared without it.

Bir özelliğin erişimcisi sanal olabilir.The accessor(s) of a property can be virtual. Bir özellik bildirimi virtual ,, abstract veya değiştiricisini içerdiğinde, override özelliğin erişimcilerle geçerli olur.When a property declaration includes a virtual, abstract, or override modifier, it applies to the accessor(s) of the property.

Dizin OluşturucularIndexers

Dizin Oluşturucu , nesnelerin diziyle aynı şekilde dizinlenmesini sağlayan bir üyedir.An indexer is a member that enables objects to be indexed in the same way as an array. Bir Dizin Oluşturucu, üyenin adının this ardından sınırlayıcılar ve arasında yazılmış bir parametre listesi gelmesi dışında bir özellik gibi bildirilmiştir [ ] .An indexer is declared like a property except that the name of the member is this followed by a parameter list written between the delimiters [ and ]. Parametreler, dizin oluşturucunun erişimcisinde kullanılabilir.The parameters are available in the accessor(s) of the indexer. Özelliklere benzer şekilde, Dizin oluşturucular okunabilir-yazılır, salt okunurdur ve salt yazılır olabilir ve bir dizin oluşturucunun erişimcisi sanal olabilir.Similar to properties, indexers can be read-write, read-only, and write-only, and the accessor(s) of an indexer can be virtual.

ListSınıfı, bir parametresi alan tek bir okuma-yazma Dizin Oluşturucu bildirir int .The List class declares a single read-write indexer that takes an int parameter. Dizin Oluşturucu, örneklerin değerleriyle dizin oluşturmanızı mümkün kılar List int .The indexer makes it possible to index List instances with int values. Örneğin:For example

List<string> names = new List<string>();
names.Add("Liz");
names.Add("Martha");
names.Add("Beth");
for (int i = 0; i < names.Count; i++) {
    string s = names[i];
    names[i] = s.ToUpper();
}

Dizin oluşturucular aşırı yüklenebilir, yani parametrelerinin sayısı veya türleri farklı olduğu sürece bir sınıfın birden çok dizin kümesini bildirebileceği anlamına gelir.Indexers can be overloaded, meaning that a class can declare multiple indexers as long as the number or types of their parameters differ.

EkinliklerEvents

Bir olay , bir sınıf veya nesnenin bildirimler sağlamasını sağlayan bir üyedir.An event is a member that enables a class or object to provide notifications. Bildirimin bir event anahtar sözcük içermesi ve türün bir temsilci türü olması dışında bir olay, bir alan gibi bildirilmiştir.An event is declared like a field except that the declaration includes an event keyword and the type must be a delegate type.

Olay üyesini bildiren bir sınıf içinde, olay bir temsilci türünün alanı gibi davranır (olay soyut değildir ve erişimcileri bildirmez).Within a class that declares an event member, the event behaves just like a field of a delegate type (provided the event is not abstract and does not declare accessors). Bu alan, olaya eklenmiş olan olay işleyicilerini temsil eden bir temsilciye bir başvuru depolar.The field stores a reference to a delegate that represents the event handlers that have been added to the event. Hiçbir olay tanıtıcısı yoksa, alanı olur null .If no event handles are present, the field is null.

List<T>Sınıfı, adlı tek bir olay üyesini bildirir Changed ve bu, listeye yeni bir öğe eklendiğini gösterir.The List<T> class declares a single event member called Changed, which indicates that a new item has been added to the list. ChangedOlay sanal yöntemi tarafından tetiklenir, bu, OnChanged önce olayın null (hiçbir işleyicinin mevcut olmadığı anlamına gelir) olup olmadığını denetler.The Changed event is raised by the OnChanged virtual method, which first checks whether the event is null (meaning that no handlers are present). Bir olayı oluşturma kavramı, olayın gösterdiği temsilciyi çağırmak için tam olarak eşdeğerdir. bu nedenle, olayları yükseltmek için özel dil yapıları yoktur.The notion of raising an event is precisely equivalent to invoking the delegate represented by the event—thus, there are no special language constructs for raising events.

İstemciler olay işleyicileri aracılığıyla olaylara tepki verir.Clients react to events through event handlers. Olay işleyicileri işleci kullanılarak eklenir += ve işleci kullanılarak kaldırılır -= .Event handlers are attached using the += operator and removed using the -= operator. Aşağıdaki örnek, olayına bir olay işleyicisi ekler Changed List<string> .The following example attaches an event handler to the Changed event of a List<string>.

using System;

class Test
{
    static int changeCount;

    static void ListChanged(object sender, EventArgs e) {
        changeCount++;
    }

    static void Main() {
        List<string> names = new List<string>();
        names.Changed += new EventHandler(ListChanged);
        names.Add("Liz");
        names.Add("Martha");
        names.Add("Beth");
        Console.WriteLine(changeCount);        // Outputs "3"
    }
}

Bir olayın temeldeki depolamanın denetiminin istendiği Gelişmiş senaryolarda, bir olay bildirimi açıkça add remove set bir özelliğin erişenine benzer bir şekilde sağlayabilir ve erişimciler sağlar.For advanced scenarios where control of the underlying storage of an event is desired, an event declaration can explicitly provide add and remove accessors, which are somewhat similar to the set accessor of a property.

İşleçlerOperators

İşleci , bir sınıfın örneklerine belirli bir ifade işlecini uygulamanın anlamını tanımlayan bir üyesidir.An operator is a member that defines the meaning of applying a particular expression operator to instances of a class. Üç tür işleç tanımlanabilir: Birli İşleçler, ikili işleçler ve dönüştürme işleçleri.Three kinds of operators can be defined: unary operators, binary operators, and conversion operators. Tüm işleçler ve olarak bildirilmelidir public static .All operators must be declared as public and static.

List<T>Sınıfı iki işleç bildirir ve operator== operator!= Bu nedenle bu işleçleri örneklere uygulayan deyimlere yeni anlamı verir List .The List<T> class declares two operators, operator== and operator!=, and thus gives new meaning to expressions that apply those operators to List instances. Özellikle, işleçler, List<T> içerilen nesnelerin her birini yöntemlerini kullanarak karşılaştıran iki örneğin eşitliğini tanımlar Equals .Specifically, the operators define equality of two List<T> instances as comparing each of the contained objects using their Equals methods. Aşağıdaki örnek, == iki örneği karşılaştırmak için işlecini kullanır List<int> .The following example uses the == operator to compare two List<int> instances.

using System;

class Test
{
    static void Main() {
        List<int> a = new List<int>();
        a.Add(1);
        a.Add(2);
        List<int> b = new List<int>();
        b.Add(1);
        b.Add(2);
        Console.WriteLine(a == b);        // Outputs "True"
        b.Add(3);
        Console.WriteLine(a == b);        // Outputs "False"
    }
}

Bu Console.WriteLine True iki liste aynı sırada aynı değerleri taşıyan aynı sayıda nesne içerdiğinden ilk çıktılar.The first Console.WriteLine outputs True because the two lists contain the same number of objects with the same values in the same order. List<T>Tanımlı değil operator== , ilki Console.WriteLine çıktıyı içeriyor False a ve b farklı örneklere başvuracaktır List<int> .Had List<T> not defined operator==, the first Console.WriteLine would have output False because a and b reference different List<int> instances.

YıkıcılarDestructors

Yıkıcı , bir sınıf örneğinin yapısını kaldırma için gereken eylemleri uygulayan bir üyesidir.A destructor is a member that implements the actions required to destruct an instance of a class. Yok ediciler parametrelere sahip olamaz, erişilebilirlik değiştiricilerine sahip olamaz ve açıkça çağrılamaz.Destructors cannot have parameters, they cannot have accessibility modifiers, and they cannot be invoked explicitly. Örnek için yıkıcısı çöp toplama sırasında otomatik olarak çağrılır.The destructor for an instance is invoked automatically during garbage collection.

Çöp toplayıcısına, nesnelerin toplanması ve yıkıcıları çalıştırma konusunda karar verirken geniş bir enlem vardır.The garbage collector is allowed wide latitude in deciding when to collect objects and run destructors. Özellikle, yıkıcı etkinleştirmeleri zamanlaması belirleyici değildir ve herhangi bir iş parçacığında yok ediciler çalıştırılabilir.Specifically, the timing of destructor invocations is not deterministic, and destructors may be executed on any thread. Bu ve diğer nedenlerden dolayı sınıfların yalnızca başka hiçbir çözüm uygulanabilir olmadığında Yıkıcılar uygulaması gerekir.For these and other reasons, classes should implement destructors only when no other solutions are feasible.

usingİfade, nesne yok etme için daha iyi bir yaklaşım sağlar.The using statement provides a better approach to object destruction.

YapılarStructs

Sınıflar gibi yapılar , veri üyeleri ve işlev üyeleri içerebilen veri yapılarıdır, ancak sınıfların aksine, yapılar değer türlerdir ve yığın ayırmayı gerektirmez.Like classes, structs are data structures that can contain data members and function members, but unlike classes, structs are value types and do not require heap allocation. Yapı türünün bir değişkeni yapının verisini doğrudan depolarken, sınıf türündeki bir değişken, dinamik olarak ayrılan bir nesneye bir başvuru depolar.A variable of a struct type directly stores the data of the struct, whereas a variable of a class type stores a reference to a dynamically allocated object. Yapı türleri Kullanıcı tarafından belirtilen devralmayı desteklemez ve tüm yapı türleri örtülü olarak türünden devralınır object .Struct types do not support user-specified inheritance, and all struct types implicitly inherit from type object.

Yapılar, özellikle değer semantiği olan küçük veri yapıları için yararlıdır.Structs are particularly useful for small data structures that have value semantics. Karmaşık sayılar, bir koordinat sistemindeki işaret veya bir sözlükte anahtar-değer çiftleri, yapı birimlerinin iyi örnekleridir.Complex numbers, points in a coordinate system, or key-value pairs in a dictionary are all good examples of structs. Küçük veri yapıları için sınıflar yerine yapıların kullanımı, bir uygulamanın gerçekleştirdiği bellek ayırma sayısında büyük bir farklılık yapabilir.The use of structs rather than classes for small data structures can make a large difference in the number of memory allocations an application performs. Örneğin, aşağıdaki program 100 noktadan oluşan bir dizi oluşturur ve başlatır.For example, the following program creates and initializes an array of 100 points. PointSınıf olarak uygulanan 101 ayrı nesneler, biri Array için ve her biri 100 öğeleri için oluşturulur.With Point implemented as a class, 101 separate objects are instantiated—one for the array and one each for the 100 elements.

class Point
{
    public int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

class Test
{
    static void Main() {
        Point[] points = new Point[100];
        for (int i = 0; i < 100; i++) points[i] = new Point(i, i);
    }
}

Alternatif olarak Point bir yapı oluşturma.An alternative is to make Point a struct.

struct Point
{
    public int x, y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }
}

Şimdi yalnızca bir nesne örneği oluşturulur — dizi için bir tane ve Point örnekler dizide satır içinde depolanır.Now, only one object is instantiated—the one for the array—and the Point instances are stored in-line in the array.

Struct oluşturucuları new işleçle çağrılır, ancak bu belleğin ayrılmakta olduğunu göstermez.Struct constructors are invoked with the new operator, but that does not imply that memory is being allocated. Bir nesne dinamik olarak tahsis etmek ve ona bir başvuru döndürmek yerine, bir struct Oluşturucusu yalnızca struct değerinin kendisini döndürür (genellikle yığındaki geçici bir konumda) ve bu değer, gereken şekilde kopyalanır.Instead of dynamically allocating an object and returning a reference to it, a struct constructor simply returns the struct value itself (typically in a temporary location on the stack), and this value is then copied as necessary.

Sınıflar ile, iki değişkenin aynı nesneye başvurması ve bu nedenle bir değişkende işlemler için diğer değişken tarafından başvurulan nesneyi etkilemesi mümkündür.With classes, it is possible for two variables to reference the same object and thus possible for operations on one variable to affect the object referenced by the other variable. Yapılar ile, her birinin kendi verilerinin bir kopyasına sahip olduğu ve bir üzerindeki işlemlerin diğerini etkilemesi mümkün değildir.With structs, the variables each have their own copy of the data, and it is not possible for operations on one to affect the other. Örneğin, aşağıdaki kod parçası tarafından üretilen çıkış, Point bir sınıf veya yapı olmasına bağlıdır.For example, the output produced by the following code fragment depends on whether Point is a class or a struct.

Point a = new Point(10, 10);
Point b = a;
a.x = 20;
Console.WriteLine(b.x);

PointBir sınıfınise, çıkış olur 20 a ve b aynı nesneye başvurur.If Point is a class, the output is 20 because a and b reference the same object. PointBir struct ise çıktı, 10 öğesinin atamanın a b değerin bir kopyasını oluşturması ve bu kopyanın sonraki atamasından etkilenmemelerdir a.x .If Point is a struct, the output is 10 because the assignment of a to b creates a copy of the value, and this copy is unaffected by the subsequent assignment to a.x.

Önceki örnek, yapıların sınırlamalarını iki vurgulamaktadır.The previous example highlights two of the limitations of structs. İlk olarak, bir yapının tamamını kopyalamak bir nesne başvurusunu kopyalamaya kıyasla genellikle daha etkilidir, bu nedenle atama ve değer parametresi, yapı ile başvuru türleriyle daha pahalı olabilir.First, copying an entire struct is typically less efficient than copying an object reference, so assignment and value parameter passing can be more expensive with structs than with reference types. İkincisi, ref ve parametreleri dışında, out yapılara başvurular oluşturmak mümkün değildir ve bu sayede kullanımları bir dizi durumda kurallar oluşturulur.Second, except for ref and out parameters, it is not possible to create references to structs, which rules out their usage in a number of situations.

DizilerArrays

*Array _, hesaplanan dizinler üzerinden erişilen çeşitli değişkenler içeren bir veri yapısıdır.An *array _ is a data structure that contains a number of variables that are accessed through computed indices. Bir dizide bulunan değişkenler, dizi *öğeleri* de denir, hepsi aynı tür olur ve bu tür dizinin _ öğe türü* olarak adlandırılır.The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the _ element type* of the array.

Dizi türleri başvuru türlerdir ve bir dizi değişkeninin bildirimi, bir dizi örneğine yönelik bir başvuru için yalnızca alan ayırın.Array types are reference types, and the declaration of an array variable simply sets aside space for a reference to an array instance. Gerçek dizi örnekleri işleci kullanılarak, çalışma zamanında dinamik olarak oluşturulur new .Actual array instances are created dynamically at run-time using the new operator. newİşlem, daha sonra örneğin ömrü boyunca düzeltilen yeni dizi örneğinin uzunluğunu belirtir.The new operation specifies the length of the new array instance, which is then fixed for the lifetime of the instance. Bir dizi öğelerinin ' den ' a kadar olan dizinleri 0 Length - 1 .The indices of the elements of an array range from 0 to Length - 1. newİşleci, bir dizinin öğelerini otomatik olarak varsayılan değerlerine başlatır. Bu, örneğin, tüm sayısal türler ve null tüm başvuru türleri için sıfırdır.The new operator automatically initializes the elements of an array to their default value, which, for example, is zero for all numeric types and null for all reference types.

Aşağıdaki örnek, bir dizi öğe oluşturur int , diziyi başlatır ve dizinin içeriğini yazdırır.The following example creates an array of int elements, initializes the array, and prints out the contents of the array.

using System;

class Test
{
    static void Main() {
        int[] a = new int[10];
        for (int i = 0; i < a.Length; i++) {
            a[i] = i * i;
        }
        for (int i = 0; i < a.Length; i++) {
            Console.WriteLine("a[{0}] = {1}", i, a[i]);
        }
    }
}

Bu örnek, *tek boyutlu dizi _ üzerinde oluşturur ve çalışır.This example creates and operates on a *single-dimensional array _. C#, *çok boyutlu dizileri* de destekler.C# also supports multi-dimensional arrays. Dizi türünün _ Rank* olarak da bilinen bir dizi türünün boyutlarının sayısı, dizi türünün köşeli ayraçları arasına yazılan virgüllerin sayısıdır.The number of dimensions of an array type, also known as the _ rank* of the array type, is one plus the number of commas written between the square brackets of the array type. Aşağıdaki örnek tek boyutlu, iki boyutlu ve üç boyutlu bir diziyi ayırır.The following example allocates a one-dimensional, a two-dimensional, and a three-dimensional array.

int[] a1 = new int[10];
int[,] a2 = new int[10, 5];
int[,,] a3 = new int[10, 5, 2];

a1Dizi 10 öğe içeriyorsa, a2 dizi 50 (10 × 5) öğesi içerir ve a3 dizi 100 (10 × 5 × 2) öğesi içerir.The a1 array contains 10 elements, the a2 array contains 50 (10 × 5) elements, and the a3 array contains 100 (10 × 5 × 2) elements.

Bir dizinin öğe türü, bir dizi türü de dahil olmak üzere herhangi bir tür olabilir.The element type of an array can be any type, including an array type. Dizi türündeki öğeleri içeren bir dizi, bazen öğe dizilerinin uzunluklarının tümünün aynı olması gerektiğinden pürüzlü dizi olarak adlandırılır.An array with elements of an array type is sometimes called a jagged array because the lengths of the element arrays do not all have to be the same. Aşağıdaki örnek dizi dizilerini ayırır int :The following example allocates an array of arrays of int:

int[][] a = new int[3][];
a[0] = new int[10];
a[1] = new int[5];
a[2] = new int[20];

İlk satır, her biri türü int[] ve her biri bir başlangıç değeri olan üç öğe içeren bir dizi oluşturur null .The first line creates an array with three elements, each of type int[] and each with an initial value of null. Sonraki satırlar, Farklı uzunluklardaki ayrı dizi örneklerine yapılan başvurularla üç öğeyi başlatır.The subsequent lines then initialize the three elements with references to individual array instances of varying lengths.

newİşleci, dizi öğelerinin başlangıç değerlerinin, sınırlayıcılar ve arasında yazılan ifadelerin listesi olan bir dizi başlatıcısı kullanılarak belirtilmesine izin verir { } .The new operator permits the initial values of the array elements to be specified using an array initializer, which is a list of expressions written between the delimiters { and }. Aşağıdaki örnek, üç öğesi ile bir ayırır ve başlatır int[] .The following example allocates and initializes an int[] with three elements.

int[] a = new int[] {1, 2, 3};

Dizi uzunluğunun ve arasındaki ifade sayısından çıkarsandığına unutmayın { } .Note that the length of the array is inferred from the number of expressions between { and }. Yerel değişken ve alan bildirimleri daha fazla kısaltılarak, dizi türünün yeniden oluşturulması gerekmez.Local variable and field declarations can be shortened further such that the array type does not have to be restated.

int[] a = {1, 2, 3};

Yukarıdaki örneklerin her ikisi de aşağıdaki gibi eşdeğerdir:Both of the previous examples are equivalent to the following:

int[] t = new int[3];
t[0] = 1;
t[1] = 2;
t[2] = 3;
int[] a = t;

ArabirimlerInterfaces

Arabirim , sınıflar ve yapılar tarafından uygulanabilecek bir sözleşmeyi tanımlar.An interface defines a contract that can be implemented by classes and structs. Arabirim, Yöntemler, özellikler, olaylar ve Dizin oluşturucular içerebilir.An interface can contain methods, properties, events, and indexers. Arabirim, tanımladığı üyelerin uygulamalarını sağlamaz; yalnızca arabirimini uygulayan sınıflar veya yapılar tarafından sağlanması gereken üyeleri belirtir.An interface does not provide implementations of the members it defines—it merely specifies the members that must be supplied by classes or structs that implement the interface.

Arabirimler birden fazla devralma kullanabilir.Interfaces may employ multiple inheritance. Aşağıdaki örnekte, arabirimi IComboBox hem hem de öğesinden devralır ITextBox IListBox .In the following example, the interface IComboBox inherits from both ITextBox and IListBox.

interface IControl
{
    void Paint();
}

interface ITextBox: IControl
{
    void SetText(string text);
}

interface IListBox: IControl
{
    void SetItems(string[] items);
}

interface IComboBox: ITextBox, IListBox {}

Sınıflar ve yapılar birden çok arabirim uygulayabilir.Classes and structs can implement multiple interfaces. Aşağıdaki örnekte, sınıfı EditBox hem hem de uygular IControl IDataBound .In the following example, the class EditBox implements both IControl and IDataBound.

interface IDataBound
{
    void Bind(Binder b);
}

public class EditBox: IControl, IDataBound
{
    public void Paint() {...}
    public void Bind(Binder b) {...}
}

Bir sınıf veya yapı belirli bir arabirimi uygularsa, bu sınıfın veya yapının örnekleri örtülü olarak bu arabirim türüne dönüştürülebilir.When a class or struct implements a particular interface, instances of that class or struct can be implicitly converted to that interface type. Örneğin:For example

EditBox editBox = new EditBox();
IControl control = editBox;
IDataBound dataBound = editBox;

Bir örneğin belirli bir arabirimi uygulamak üzere statik olarak bilinmediği durumlarda dinamik tür atamaları kullanılabilir.In cases where an instance is not statically known to implement a particular interface, dynamic type casts can be used. Örneğin, aşağıdaki deyimler bir nesnenin IControl ve arabirim uygulamalarının elde edileceği dinamik tür yayınlarını kullanır IDataBound .For example, the following statements use dynamic type casts to obtain an object's IControl and IDataBound interface implementations. Nesnenin gerçek türü olduğundan, yayınlar başarılı olur EditBox .Because the actual type of the object is EditBox, the casts succeed.

object obj = new EditBox();
IControl control = (IControl)obj;
IDataBound dataBound = (IDataBound)obj;

Önceki EditBox sınıfta, Paint IControl arabiriminden yöntemi ve Bind arabiriminden yöntemi, IDataBound Üyeler kullanılarak uygulanır public .In the previous EditBox class, the Paint method from the IControl interface and the Bind method from the IDataBound interface are implemented using public members. C# Ayrıca, sınıf veya yapının üyeleri yapmaktan kaçınmasına engel olabilecek Açık arabirim üye uygulamalarını da destekler public .C# also supports explicit interface member implementations, using which the class or struct can avoid making the members public. Açık arabirim üyesi uygulama, tam nitelikli arabirim üye adı kullanılarak yazılır.An explicit interface member implementation is written using the fully qualified interface member name. Örneğin, EditBox sınıfı IControl.Paint IDataBound.Bind aşağıdaki gibi açık arabirim üye uygulamalarını kullanarak ve yöntemlerini uygulayabilir.For example, the EditBox class could implement the IControl.Paint and IDataBound.Bind methods using explicit interface member implementations as follows.

public class EditBox: IControl, IDataBound
{
    void IControl.Paint() {...}
    void IDataBound.Bind(Binder b) {...}
}

Açık arabirim üyelerine yalnızca arabirim türü aracılığıyla erişilebilir.Explicit interface members can only be accessed via the interface type. Örneğin, IControl.Paint önceki sınıf tarafından sağlanmış olan uygulama, EditBox yalnızca öncelikle EditBox arabirim türüne başvuru dönüştürülürken çağrılabilir IControl .For example, the implementation of IControl.Paint provided by the previous EditBox class can only be invoked by first converting the EditBox reference to the IControl interface type.

EditBox editBox = new EditBox();
editBox.Paint();                        // Error, no such method
IControl control = editBox;
control.Paint();                        // Ok

NumaralandırmalarEnums

Sabit listesi türü , adlandırılmış sabitler kümesi olan ayrı bir değer türüdür.An enum type is a distinct value type with a set of named constants. Aşağıdaki örnek,,, Color ve üç sabit değeri olan adlı bir sabit listesi türü bildirir ve kullanır Red Green Blue .The following example declares and uses an enum type named Color with three constant values, Red, Green, and Blue.

using System;

enum Color
{
    Red,
    Green,
    Blue
}

class Test
{
    static void PrintColor(Color color) {
        switch (color) {
            case Color.Red:
                Console.WriteLine("Red");
                break;
            case Color.Green:
                Console.WriteLine("Green");
                break;
            case Color.Blue:
                Console.WriteLine("Blue");
                break;
            default:
                Console.WriteLine("Unknown color");
                break;
        }
    }

    static void Main() {
        Color c = Color.Red;
        PrintColor(c);
        PrintColor(Color.Blue);
    }
}

Her sabit listesi türünün, enum türünün temel alınan türü olarak adlandırılan karşılık gelen bir integral türü vardır.Each enum type has a corresponding integral type called the underlying type of the enum type. Temel alınan bir türü açıkça bildirmiyor bir sabit listesi türü, temel alınan bir tür içerir int .An enum type that does not explicitly declare an underlying type has an underlying type of int. Sabit listesi türünün depolama biçimi ve olası değerlerinin aralığı, temel alınan türüne göre belirlenir.An enum type's storage format and range of possible values are determined by its underlying type. Bir numaralandırma türünün üzerinde sürebelirlenen değerler kümesi, sabit listesi üyeleri tarafından sınırlı değildir.The set of values that an enum type can take on is not limited by its enum members. Özellikle, bir sabit listesinin temel alınan türünün herhangi bir değeri, sabit listesi türüne dönüşebilir ve bu sabit listesi türünün ayrı bir geçerli değeridir.In particular, any value of the underlying type of an enum can be cast to the enum type and is a distinct valid value of that enum type.

Aşağıdaki örnek, Alignment temel alınan türü ile adlı bir sabit listesi türü bildirir sbyte .The following example declares an enum type named Alignment with an underlying type of sbyte.

enum Alignment: sbyte
{
    Left = -1,
    Center = 0,
    Right = 1
}

Önceki örnekte gösterildiği gibi, enum üye bildirimi üyenin değerini belirten bir sabit ifade içerebilir.As shown by the previous example, an enum member declaration can include a constant expression that specifies the value of the member. Her sabit listesi üyesinin sabit değeri, sabit listesinin temel alınan türü aralığında olmalıdır.The constant value for each enum member must be in the range of the underlying type of the enum. Sabit listesi üyesi bildirimi açıkça bir değer belirtmezse, üyeye sıfır değeri verilir (sabit listesi türünde ilk üye ise) veya metin içeriğini eklemek önceki enum üyesinin değeri ve bir.When an enum member declaration does not explicitly specify a value, the member is given the value zero (if it is the first member in the enum type) or the value of the textually preceding enum member plus one.

Sabit listesi değerleri tamsayı değerlerine dönüştürülebilir ve tür atamaları kullanılarak tam tersi olabilir.Enum values can be converted to integral values and vice versa using type casts. Örneğin:For example

int i = (int)Color.Blue;        // int i = 2;
Color c = (Color)2;             // Color c = Color.Blue;

Herhangi bir sabit listesi türünün varsayılan değeri, enum türüne dönüştürülen tam sayı değeridir.The default value of any enum type is the integral value zero converted to the enum type. Değişkenlerin otomatik olarak varsayılan bir değere başlatıldığı durumlarda, bu değer enum türü değişkenlerine verilen değerdir.In cases where variables are automatically initialized to a default value, this is the value given to variables of enum types. Bir sabit listesi türünün varsayılan değerinin kolayca kullanılabilmesi için, değişmez değer 0 örtülü olarak herhangi bir numaralandırma türüne dönüştürülür.In order for the default value of an enum type to be easily available, the literal 0 implicitly converts to any enum type. Bu nedenle, aşağıdakilere izin verilir.Thus, the following is permitted.

Color c = 0;

TemsilcilerDelegates

Bir temsilci türü , belirli bir parametre listesi ve dönüş türü olan yöntemlere yapılan başvuruları temsil eder.A delegate type represents references to methods with a particular parameter list and return type. Temsilciler, yöntemleri değişkenlere atanabilecek ve parametre olarak geçirilen varlıklar olarak işleme olanağı tanır.Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Temsilciler, bazı diğer dillerde bulunan işlev işaretçileri kavramına benzerdir, ancak işlev işaretçilerinden farklı olarak Temsilciler nesne yönelimli ve tür açısından güvenlidir.Delegates are similar to the concept of function pointers found in some other languages, but unlike function pointers, delegates are object-oriented and type-safe.

Aşağıdaki örnek adlı bir temsilci türü bildirir ve kullanır Function .The following example declares and uses a delegate type named Function.

using System;

delegate double Function(double x);

class Multiplier
{
    double factor;

    public Multiplier(double factor) {
        this.factor = factor;
    }

    public double Multiply(double x) {
        return x * factor;
    }
}

class Test
{
    static double Square(double x) {
        return x * x;
    }

    static double[] Apply(double[] a, Function f) {
        double[] result = new double[a.Length];
        for (int i = 0; i < a.Length; i++) result[i] = f(a[i]);
        return result;
    }

    static void Main() {
        double[] a = {0.0, 0.5, 1.0};
        double[] squares = Apply(a, Square);
        double[] sines = Apply(a, Math.Sin);
        Multiplier m = new Multiplier(2.0);
        double[] doubles =  Apply(a, m.Multiply);
    }
}

Temsilci türünün bir örneği, Function double bağımsız değişken alan ve bir değer döndüren herhangi bir yönteme başvurabilir double .An instance of the Function delegate type can reference any method that takes a double argument and returns a double value. ApplyYöntemi, bir öğesine verilen Function öğeleri uygular double[] ve double[] sonuçları ile döndürür.The Apply method applies a given Function to the elements of a double[], returning a double[] with the results. MainYönteminde, Apply bir öğesine üç farklı işlev uygulamak için kullanılır double[] .In the Main method, Apply is used to apply three different functions to a double[].

Bir temsilci, statik bir yönteme (örn Square Math.Sin . veya önceki örnekte olduğu gibi) ya da bir örnek yöntemine (örneğin m.Multiply , önceki örnekte olduğu gibi) başvurabilir.A delegate can reference either a static method (such as Square or Math.Sin in the previous example) or an instance method (such as m.Multiply in the previous example). Örnek yönteme başvuran bir temsilci belirli bir nesneye de başvurur ve örnek yöntemi temsilci aracılığıyla çağrıldığında, bu nesne this çağrı içinde olur.A delegate that references an instance method also references a particular object, and when the instance method is invoked through the delegate, that object becomes this in the invocation.

Temsilciler, anında oluşturulan "satır içi Yöntemler" olan anonim işlevler kullanılarak da oluşturulabilir.Delegates can also be created using anonymous functions, which are "inline methods" that are created on the fly. Anonim işlevler, çevresindeki yöntemlerin yerel değişkenlerini görebilir.Anonymous functions can see the local variables of the surrounding methods. Bu nedenle, yukarıdaki çarpan örneği bir sınıf kullanılmadan daha kolay yazılabilir Multiplier :Thus, the multiplier example above can be written more easily without using a Multiplier class:

double[] doubles =  Apply(a, (double x) => x * 2.0);

Bir temsilcinin ilgi çekici ve yararlı bir özelliği, başvurduğu yöntemin sınıfını bilmez veya ilgilenmez; her önemli şey, başvurulan yöntemin aynı parametrelere sahip olması ve temsilciyle aynı türde dönüş türüdür.An interesting and useful property of a delegate is that it does not know or care about the class of the method it references; all that matters is that the referenced method has the same parameters and return type as the delegate.

ÖzniteliklerAttributes

Bir C# programındaki türler, Üyeler ve diğer varlıklar, davranışlarının belirli yönlerini denetleyen değiştiricileri destekler.Types, members, and other entities in a C# program support modifiers that control certain aspects of their behavior. Örneğin, bir yöntemin erişilebilirliği,,, public protected internal ve değiştiricileri kullanılarak denetlenir private .For example, the accessibility of a method is controlled using the public, protected, internal, and private modifiers. C#, bu özelliği, Kullanıcı tanımlı bildirime dayalı bilgi türleri program varlıklarına iliştirilebilecek ve çalışma zamanında alınabilecek şekilde genelleştirir.C# generalizes this capability such that user-defined types of declarative information can be attached to program entities and retrieved at run-time. Programlar, öznitelikleri tanımlayarak ve kullanarak bu ek bildirime dayalı bilgileri belirtir.Programs specify this additional declarative information by defining and using attributes.

Aşağıdaki örnek, HelpAttribute ilişkili belgelerinin bağlantılarını sağlamak için program varlıklarına yerleştirilebilecek bir özniteliği bildirir.The following example declares a HelpAttribute attribute that can be placed on program entities to provide links to their associated documentation.

using System;

public class HelpAttribute: Attribute
{
    string url;
    string topic;

    public HelpAttribute(string url) {
        this.url = url;
    }

    public string Url {
        get { return url; }
    }

    public string Topic {
        get { return topic; }
        set { topic = value; }
    }
}

Tüm öznitelik sınıfları System.Attribute , .NET Framework tarafından belirtilen temel sınıftan türetilir.All attribute classes derive from the System.Attribute base class provided by the .NET Framework. Öznitelikler, ilişkili bildirimden hemen önceki köşeli parantez içinde, adı ve bağımsız değişkenlerle birlikte uygulanabilir.Attributes can be applied by giving their name, along with any arguments, inside square brackets just before the associated declaration. Bir özniteliğin adı içinde biterse Attribute , özniteliğe başvuruluyorsa adın bu bölümü atlanabilir.If an attribute's name ends in Attribute, that part of the name can be omitted when the attribute is referenced. Örneğin, HelpAttribute özniteliği aşağıdaki gibi kullanılabilir.For example, the HelpAttribute attribute can be used as follows.

[Help("http://msdn.microsoft.com/.../MyClass.htm")]
public class Widget
{
    [Help("http://msdn.microsoft.com/.../MyClass.htm", Topic = "Display")]
    public void Display(string text) {}
}

Bu örnek, sınıfına HelpAttribute öğesine ve başka bir sınıftaki yöntemine bir iliştirir Widget HelpAttribute Display .This example attaches a HelpAttribute to the Widget class and another HelpAttribute to the Display method in the class. Öznitelik sınıfının ortak oluşturucuları, özniteliği bir program varlığına eklendiğinde sağlanması gereken bilgileri denetler.The public constructors of an attribute class control the information that must be provided when the attribute is attached to a program entity. Öznitelik sınıfının genel okuma-yazma özelliklerine (daha önce özelliğine başvuru gibi) başvurarak ek bilgiler sunulabilir Topic .Additional information can be provided by referencing public read-write properties of the attribute class (such as the reference to the Topic property previously).

Aşağıdaki örnek, belirli bir program varlığı için öznitelik bilgilerinin yansıma kullanarak çalışma zamanında nasıl alınamayacağını gösterir.The following example shows how attribute information for a given program entity can be retrieved at run-time using reflection.

using System;
using System.Reflection;

class Test
{
    static void ShowHelp(MemberInfo member) {
        HelpAttribute a = Attribute.GetCustomAttribute(member,
            typeof(HelpAttribute)) as HelpAttribute;
        if (a == null) {
            Console.WriteLine("No help for {0}", member);
        }
        else {
            Console.WriteLine("Help for {0}:", member);
            Console.WriteLine("  Url={0}, Topic={1}", a.Url, a.Topic);
        }
    }

    static void Main() {
        ShowHelp(typeof(Widget));
        ShowHelp(typeof(Widget).GetMethod("Display"));
    }
}

Belirli bir öznitelik yansıma aracılığıyla istendiğinde, öznitelik sınıfı için Oluşturucu program kaynağında sağlanan bilgilerle çağrılır ve sonuçta elde edilen öznitelik örneği döndürülür.When a particular attribute is requested through reflection, the constructor for the attribute class is invoked with the information provided in the program source, and the resulting attribute instance is returned. Özellikler aracılığıyla ek bilgiler sağlanmışsa, öznitelik örneği döndürülmeden önce bu özellikler verilen değerlere ayarlanır.If additional information was provided through properties, those properties are set to the given values before the attribute instance is returned.