Temel kavramlarBasic concepts

Uygulama başlatmaApplication Startup

Giriş noktası _ içeren bir derlemeye _uygulama*_ denir.An assembly that has an entry point _ is called an _application*_. Bir uygulama çalıştırıldığında yeni bir _ uygulama etki alanı* oluşturulur.When an application is run, a new _ application domain* is created. Bir uygulamanın birçok farklı örneği aynı anda aynı makinede bulunabilir ve her birinin kendi uygulama etki alanına sahip olabilir.Several different instantiations of an application may exist on the same machine at the same time, and each has its own application domain.

Uygulama etki alanı, uygulama durumu için kapsayıcı görevi gören uygulama yalıtımına izin veriyor.An application domain enables application isolation by acting as a container for application state. Uygulama etki alanı, uygulamada tanımlanan türler ve kullandığı sınıf kitaplıklarında bir kapsayıcı ve sınır görevi görür.An application domain acts as a container and boundary for the types defined in the application and the class libraries it uses. Bir uygulama etki alanına yüklenen türler, başka bir uygulama etki alanına yüklenen aynı türden farklıdır ve nesne örnekleri uygulama etki alanları arasında doğrudan paylaşılmaz.Types loaded into one application domain are distinct from the same type loaded into another application domain, and instances of objects are not directly shared between application domains. Örneğin, her bir uygulama etki alanının bu türler için kendi statik değişkenlerinin kopyası vardır ve bir tür için statik bir Oluşturucu uygulama etki alanı başına en çok bir kez çalıştırılır.For instance, each application domain has its own copy of static variables for these types, and a static constructor for a type is run at most once per application domain. Uygulamalar, uygulama etki alanlarının oluşturulması ve yok edilmesi için uygulamaya özgü ilke veya mekanizmalar sağlamak üzere ücretsizdir.Implementations are free to provide implementation-specific policy or mechanisms for the creation and destruction of application domains.

Uygulama başlatma , yürütme ortamı, uygulamanın giriş noktası olarak adlandırılan belirlenmiş bir yöntemi çağırdığında oluşur.Application startup occurs when the execution environment calls a designated method, which is referred to as the application's entry point. Bu giriş noktası yöntemi her zaman adlandırılır Main ve aşağıdaki imzalardan birine sahip olabilir:This entry point method is always named Main, and can have one of the following signatures:

static void Main() {...}

static void Main(string[] args) {...}

static int Main() {...}

static int Main(string[] args) {...}

Gösterildiği gibi, giriş noktası isteğe bağlı olarak bir int değer döndürebilir.As shown, the entry point may optionally return an int value. Bu dönüş değeri uygulama sonlandırmada (Uygulama sonlandırma) kullanılır.This return value is used in application termination (Application termination).

Giriş noktası, isteğe bağlı olarak bir biçimsel parametreye sahip olabilir.The entry point may optionally have one formal parameter. Parametre herhangi bir ada sahip olabilir, ancak parametrenin türü olmalıdır string[] .The parameter may have any name, but the type of the parameter must be string[]. Biçimsel parametre varsa, yürütme ortamı, string[] uygulama başlatıldığında belirtilen komut satırı bağımsız değişkenlerini içeren bir bağımsız değişken oluşturur ve geçirir.If the formal parameter is present, the execution environment creates and passes a string[] argument containing the command-line arguments that were specified when the application was started. string[]Bağımsız değişken hiçbir şekilde null değildir, ancak komut satırı bağımsız değişkenleri belirtilmemişse sıfır uzunluğuna sahip olabilir.The string[] argument is never null, but it may have a length of zero if no command-line arguments were specified.

C# yöntemi aşırı yüklemeyi desteklediğinden, bir sınıf veya yapı, her yöntemin farklı bir imzaya sahip olan birden çok tanımını içerebilir.Since C# supports method overloading, a class or struct may contain multiple definitions of some method, provided each has a different signature. Ancak, tek bir program içinde, hiçbir sınıf veya yapı, Main tanımı bir uygulama giriş noktası olarak kullanılmak üzere niteleyen adlı birden fazla yöntem içerebilir.However, within a single program, no class or struct may contain more than one method called Main whose definition qualifies it to be used as an application entry point. Diğer aşırı yüklenmiş sürümlerine Main izin verilir, ancak birden fazla parametreye sahip olmaları veya yalnızca parametresi türü dışında string[] .Other overloaded versions of Main are permitted, however, provided they have more than one parameter, or their only parameter is other than type string[].

Bir uygulama birden fazla sınıftan veya yapıların üzerinde oluşturulabilir.An application can be made up of multiple classes or structs. Bu sınıfların veya yapıların birden fazla olması, Main tanımı bir uygulama giriş noktası olarak kullanılmak üzere niteleyen adlı bir yöntemi içermesi olabilir.It is possible for more than one of these classes or structs to contain a method called Main whose definition qualifies it to be used as an application entry point. Bu gibi durumlarda, giriş noktası olarak bu yöntemlerden birini seçmek için bir dış mekanizmanın (bir komut satırı derleyici seçeneği gibi) kullanılması gerekir Main .In such cases, an external mechanism (such as a command-line compiler option) must be used to select one of these Main methods as the entry point.

C# ' de, her yöntemin bir sınıfın veya yapının üyesi olarak tanımlanması gerekir.In C#, every method must be defined as a member of a class or struct. Genellikle, bir yöntemin tanımlanmış erişilebilirliği (tanımlanmış erişilebilirlik), bildiriminde belirtilen erişim değiştiricilerine (erişim değiştiricilerine) göre belirlenir ve benzer şekilde, bir türün tanımlanmış erişilebilirliği, bildiriminde belirtilen erişim değiştiricilerine göre belirlenir.Ordinarily, the declared accessibility (Declared accessibility) of a method is determined by the access modifiers (Access modifiers) specified in its declaration, and similarly the declared accessibility of a type is determined by the access modifiers specified in its declaration. Verilen bir türün belirli bir yönteminin çağrılabilir olması için, hem tür hem de üyenin erişilebilir olması gerekir.In order for a given method of a given type to be callable, both the type and the member must be accessible. Ancak, uygulama giriş noktası özel bir durumdur.However, the application entry point is a special case. Özellikle, yürütme ortamı uygulamanın giriş noktasına, kendisine ait erişilebilirliği ve kapsayan tür bildirimlerinin belirtilen erişilebilirliğinden bağımsız olarak erişebilir.Specifically, the execution environment can access the application's entry point regardless of its declared accessibility and regardless of the declared accessibility of its enclosing type declarations.

Uygulama giriş noktası yöntemi bir genel sınıf bildiriminde bulunmayabilir.The application entry point method may not be in a generic class declaration.

Diğer tüm anlarda giriş noktası yöntemleri giriş noktaları olmayan gibi davranır.In all other respects, entry point methods behave like those that are not entry points.

Uygulama sonlandırmaApplication termination

Uygulama sonlandırması denetim yürütme ortamına geri döndürür.Application termination returns control to the execution environment.

Uygulamanın *giriş noktası _ yönteminin dönüş türü ise int , döndürülen değer uygulamanın _ sonlandırma durum kodu * olarak işlev görür.If the return type of the application's entry point _ method is int, the value returned serves as the application's _termination status code**. Bu kodun amacı, yürütme ortamında başarı veya başarısızlık iletişimine iletişim sağlamaktır.The purpose of this code is to allow communication of success or failure to the execution environment.

Giriş noktası yönteminin dönüş türü ise, void } Bu yöntemi sonlandıran veya ifadesi olmayan bir deyimi yürüten sağ küme ayracı () ile eriştikten sonra return sonlandırma durum koduna neden olur 0 .If the return type of the entry point method is void, reaching the right brace (}) which terminates that method, or executing a return statement that has no expression, results in a termination status code of 0.

Bir uygulamanın sonlandırmasından önce, henüz atık olarak toplanmamış tüm nesneleri için yok ediciler, temizleme gizlenmediği (örneğin, kitaplık yöntemine yapılan bir çağrı tarafından GC.SuppressFinalize ) çağırılır.Prior to an application's termination, destructors for all of its objects that have not yet been garbage collected are called, unless such cleanup has been suppressed (by a call to the library method GC.SuppressFinalize, for example).

BildirimlerDeclarations

Bir C# programındaki bildirimler programın anayent öğelerini tanımlar.Declarations in a C# program define the constituent elements of the program. C# programları, tür bildirimleri ve iç içe ad alanı bildirimleri içerebilen ad alanları (ad alanları) kullanılarak düzenlenir.C# programs are organized using namespaces (Namespaces), which can contain type declarations and nested namespace declarations. Tür bildirimleri (tür bildirimleri), sınıfları (sınıflar), yapıları (yapılar), arabirimleri (arabirimleri), numaralandırmalar (numaralandırmalar) ve temsilcileri (Temsilciler) tanımlamak için kullanılır.Type declarations (Type declarations) are used to define classes (Classes), structs (Structs), interfaces (Interfaces), enums (Enums), and delegates (Delegates). Tür bildiriminde izin verilen üye türleri tür bildiriminin biçimine bağlıdır.The kinds of members permitted in a type declaration depend on the form of the type declaration. Örneğin, sınıf bildirimleri sabitler (sabitler), alanlar (alanlar), Yöntemler (Yöntemler), Özellikler (Özellikler), Olaylar (Olaylar), Dizin oluşturucular (Dizinoluşturucular), işleçler (Işleçler), örnek oluşturucular (örnek oluşturucular), statik oluşturucular (statik oluşturucular), Yıkıcılar (Yıkıcılar) ve iç içe türler (iç içe türler) için bildirimler içerebilir.For instance, class declarations can contain declarations for constants (Constants), fields (Fields), methods (Methods), properties (Properties), events (Events), indexers (Indexers), operators (Operators), instance constructors (Instance constructors), static constructors (Static constructors), destructors (Destructors), and nested types (Nested types).

Bildirim, bildirimin ait olduğu bildirim alanında bir ad tanımlar.A declaration defines a name in the declaration space to which the declaration belongs. Aşırı yüklenmiş Üyeler hariç (imzalar ve aşırı yükleme), bir bildirim alanında aynı ada sahip üyeleri tanıtan iki veya daha fazla bildirime sahip bir derleme zamanı hatasıdır.Except for overloaded members (Signatures and overloading), it is a compile-time error to have two or more declarations that introduce members with the same name in a declaration space. Bir bildirim alanının aynı ada sahip farklı üye türleri içermesi hiçbir şekilde mümkün değildir.It is never possible for a declaration space to contain different kinds of members with the same name. Örneğin, bir bildirim alanı hiçbir şekilde bir alanı ve aynı ada sahip bir yöntemi içeremez.For example, a declaration space can never contain a field and a method by the same name.

Aşağıda açıklandığı gibi birkaç farklı türde bildirim alanı vardır.There are several different types of declaration spaces, as described in the following.

  • Bir programın tüm kaynak dosyalarında, kapsayan namespace_declaration olmayan namespace_member_declaration s, genel bildirim alanı olarak adlandırılan tek bir Birleşik bildirim alanının üyeleridir.Within all source files of a program, namespace_member_declaration s with no enclosing namespace_declaration are members of a single combined declaration space called the global declaration space.
  • Bir programın tüm kaynak dosyaları içinde, aynı tam ad alanı adına sahip namespace_declaration s içindeki namespace_member_declaration s tek bir Birleşik bildirim alanının üyeleridir.Within all source files of a program, namespace_member_declaration s within namespace_declaration s that have the same fully qualified namespace name are members of a single combined declaration space.
  • Her sınıf, yapı veya arabirim bildirimi yeni bir bildirim alanı oluşturur.Each class, struct, or interface declaration creates a new declaration space. Adlar, bu bildirim alanına class_member_declaration s, struct_member_declaration s, interface_member_declaration s veya type_parameter s aracılığıyla tanıtılmıştır.Names are introduced into this declaration space through class_member_declaration s, struct_member_declaration s, interface_member_declaration s, or type_parameter s. Aşırı yüklenmiş örnek Oluşturucu bildirimleri ve statik Oluşturucu bildirimleri dışında, bir sınıf veya yapı sınıfı veya struct ile aynı ada sahip bir üye bildirimi içeremez.Except for overloaded instance constructor declarations and static constructor declarations, a class or struct cannot contain a member declaration with the same name as the class or struct. Bir sınıf, yapı veya arabirim, aşırı yüklenmiş yöntemlerin ve Dizin oluşturucuların bildirimine izin verir.A class, struct, or interface permits the declaration of overloaded methods and indexers. Ayrıca, bir sınıf veya yapı, aşırı yüklenmiş örnek oluşturucuların ve işleçlerin bildirimine izin verir.Furthermore, a class or struct permits the declaration of overloaded instance constructors and operators. Örneğin, bir sınıf, yapı veya arabirim aynı ada sahip birden çok yöntem bildirimi içerebilir, bu yöntem bildirimleri imzasında (imzalar ve aşırı yükleme) farklı olabilir.For example, a class, struct, or interface may contain multiple method declarations with the same name, provided these method declarations differ in their signature (Signatures and overloading). Temel sınıfların bir sınıfın bildirim alanına katkıda bulunmadığını ve temel arabirimlerin bir arabirimin bildirim alanına katkıda bulunmayacağını unutmayın.Note that base classes do not contribute to the declaration space of a class, and base interfaces do not contribute to the declaration space of an interface. Bu nedenle, türetilmiş bir sınıfın veya arabirimin devralınan üye ile aynı ada sahip bir üyeyi bildirmesine izin verilir.Thus, a derived class or interface is allowed to declare a member with the same name as an inherited member. Bu tür bir üye devralınan üyeyi gizleyecek şekilde kabul edilir.Such a member is said to hide the inherited member.
  • Her temsilci bildirimi yeni bir bildirim alanı oluşturur.Each delegate declaration creates a new declaration space. Adlar, bu bildirim alanına biçimsel parametreler (fixed_parameter s ve parameter_array s) ve type_parameter s aracılığıyla tanıtılmıştır.Names are introduced into this declaration space through formal parameters (fixed_parameter s and parameter_array s) and type_parameter s.
  • Her numaralandırma bildirimi yeni bir bildirim alanı oluşturur.Each enumeration declaration creates a new declaration space. Adlar bu bildirim alanına enum_member_declarations aracılığıyla tanıtılmıştır.Names are introduced into this declaration space through enum_member_declarations.
  • Her yöntem bildirimi, Dizin Oluşturucu bildirimi, işleç bildirimi, örnek Oluşturucu bildirimi ve anonim işlev *yerel değişken bildirim alanı _ adlı yeni bir bildirim alanı oluşturur.Each method declaration, indexer declaration, operator declaration, instance constructor declaration and anonymous function creates a new declaration space called a *local variable declaration space _. Adlar, bu bildirim alanına biçimsel parametreler (_fixed_parameter * s ve parameter_array s) ve type_parameter s aracılığıyla tanıtılmıştır.Names are introduced into this declaration space through formal parameters (_fixed_parameter*s and parameter_array s) and type_parameter s. İşlev üyesi veya anonim işlevin gövdesi, varsa, yerel değişken bildirim alanı içinde iç içe olarak kabul edilir.The body of the function member or anonymous function, if any, is considered to be nested within the local variable declaration space. Yerel bir değişken bildirim alanı ve aynı ada sahip öğeleri içermesi için iç içe geçmiş yerel değişken bildirim alanı için bir hatadır.It is an error for a local variable declaration space and a nested local variable declaration space to contain elements with the same name. Bu nedenle, iç içe geçmiş bir bildirim alanı içinde, bir yerel değişken veya sabit değeri, kapsayan bir bildirim alanında yerel bir değişkenle veya sabitle aynı ada sahip olabilir.Thus, within a nested declaration space it is not possible to declare a local variable or constant with the same name as a local variable or constant in an enclosing declaration space. İki bildirim alanı, hiçbir bildirim alanı diğeri içermediği sürece aynı ada sahip öğeleri içermesi için mümkündür.It is possible for two declaration spaces to contain elements with the same name as long as neither declaration space contains the other.
  • Her bir blok veya switch_block , ayrıca bir for, foreach ve using ifadesi, yerel değişkenler ve yerel sabitler için yerel bir değişken bildirim alanı oluşturur.Each block or switch_block , as well as a for, foreach and using statement, creates a local variable declaration space for local variables and local constants . Adlar bu bildirim alanına local_variable_declaration s ve local_constant_declaration s aracılığıyla tanıtılmıştır.Names are introduced into this declaration space through local_variable_declaration s and local_constant_declaration s. Bir işlev üyesinin veya anonim işlevin gövdesi içinde veya içinde oluşan blokların, parametreleri için bu işlevler tarafından tanımlanan yerel değişken bildirim alanı içinde iç içe geçmiş olduğunu unutmayın.Note that blocks that occur as or within the body of a function member or anonymous function are nested within the local variable declaration space declared by those functions for their parameters. Bu nedenle, örneğin bir yerel değişkene ve aynı ada sahip bir parametreye sahip bir yöntem olması hatadır.Thus it is an error to have e.g. a method with a local variable and a parameter of the same name.
  • Her blok veya switch_block , Etiketler için ayrı bir bildirim alanı oluşturur.Each block or switch_block creates a separate declaration space for labels. Adlar, labeled_statement s aracılığıyla bu bildirim alanına tanıtılmıştır ve adlara goto_statement s aracılığıyla başvurulur.Names are introduced into this declaration space through labeled_statement s, and the names are referenced through goto_statement s. Bir bloğun etiket bildirim alanı , iç içe geçmiş blokları içerir.The label declaration space of a block includes any nested blocks. Bu nedenle, iç içe bir blok içinde, kapsayan bir blok içindeki bir etiketle aynı ada sahip bir etiketi bildirmek mümkün değildir.Thus, within a nested block it is not possible to declare a label with the same name as a label in an enclosing block.

Adların bildirildiği metin sırası genellikle anlamlı değildir.The textual order in which names are declared is generally of no significance. Özellikle, metinsel sıralama, ad alanları, sabitler, Yöntemler, özellikler, olaylar, Dizin oluşturucular, işleçler, örnek oluşturucular, Yıkıcılar, statik oluşturucular ve türler için önemli değildir.In particular, textual order is not significant for the declaration and use of namespaces, constants, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors, and types. Bildirim sırası aşağıdaki yollarla önemlidir:Declaration order is significant in the following ways:

  • Alan bildirimleri ve yerel değişken bildirimleri için bildirim sırası, başlatıcılarının (varsa) yürütülme sırasını belirler.Declaration order for field declarations and local variable declarations determines the order in which their initializers (if any) are executed.
  • Yerel değişkenlerin kullanılmadan önce tanımlanması gerekir (kapsamlar).Local variables must be defined before they are used (Scopes).
  • Constant_expression değerleri atlandığında enum üye bildirimleri (enum üyeleri) için bildirim sırası önemlidir.Declaration order for enum member declarations (Enum members) is significant when constant_expression values are omitted.

Bir ad alanının bildirim alanı "açık sona erdi" ve aynı tam ada sahip iki ad alanı bildirimi aynı bildirim alanına katkıda bulunur.The declaration space of a namespace is "open ended", and two namespace declarations with the same fully qualified name contribute to the same declaration space. Örneğin:For example

namespace Megacorp.Data
{
    class Customer
    {
        ...
    }
}

namespace Megacorp.Data
{
    class Order
    {
        ...
    }
}

Yukarıdaki iki ad alanı bildirimi aynı bildirim alanına katkıda bulunur ve bu durumda, tam olarak nitelenmiş adlara sahip iki sınıf bildiriyor Megacorp.Data.Customer Megacorp.Data.Order .The two namespace declarations above contribute to the same declaration space, in this case declaring two classes with the fully qualified names Megacorp.Data.Customer and Megacorp.Data.Order. İki bildirim aynı bildirim alanına katkıda bulunduğundan, her biri aynı ada sahip bir sınıfın bildirimini içeriyorsa, derleme zamanı hatasına neden olur.Because the two declarations contribute to the same declaration space, it would have caused a compile-time error if each contained a declaration of a class with the same name.

Yukarıda belirtildiği gibi, bir bloğun bildirim alanı, iç içe geçmiş blokları içerir.As specified above, the declaration space of a block includes any nested blocks. Bu nedenle, aşağıdaki örnekte, F ve G Yöntemleri derleme zamanı hatasına neden olur çünkü ad i dış blokta bildirildiği ve iç blokta yeniden bildirilemez.Thus, in the following example, the F and G methods result in a compile-time error because the name i is declared in the outer block and cannot be redeclared in the inner block. Ancak, H iki, I i iç içe olmayan ayrı bloklarda bildirildiği için ve yöntemleri geçerlidir.However, the H and I methods are valid since the two i's are declared in separate non-nested blocks.

class A
{
    void F() {
        int i = 0;
        if (true) {
            int i = 1;            
        }
    }

    void G() {
        if (true) {
            int i = 0;
        }
        int i = 1;                
    }

    void H() {
        if (true) {
            int i = 0;
        }
        if (true) {
            int i = 1;
        }
    }

    void I() {
        for (int i = 0; i < 10; i++)
            H();
        for (int i = 0; i < 10; i++)
            H();
    }
}

ÜyelerMembers

Ad alanları ve türlerin üyeleri vardır.Namespaces and types have members. Bir varlığın üyeleri, varlığa yönelik bir başvuruya ve ardından "" belirtecinin ardından üyenin adından sonra gelen nitelenmiş adı kullanarak kullanılabilir . .The members of an entity are generally available through the use of a qualified name that starts with a reference to the entity, followed by a "." token, followed by the name of the member.

Bir türün üyeleri tür bildiriminde bildirilmiştir veya türün temel sınıfından devralınır .Members of a type are either declared in the type declaration or inherited from the base class of the type. Bir tür taban sınıftan devralırsa, örnek oluşturucular, Yıkıcılar ve statik oluşturucular hariç olmak üzere temel sınıfın tüm üyeleri türetilmiş türün üyesi olur.When a type inherits from a base class, all members of the base class, except instance constructors, destructors and static constructors, become members of the derived type. Bir temel sınıf üyesinin tanımlanmış erişilebilirliği üyenin devralınıp alınmayacağını denetlemez — devralma, örnek Oluşturucu, statik oluşturucu veya yıkıcı olmayan herhangi bir üyeye genişletilir.The declared accessibility of a base class member does not control whether the member is inherited—inheritance extends to any member that isn't an instance constructor, static constructor, or destructor. Ancak, devralınan bir üye, bildirildiği Erişilebilirlik (tarafındantanımlanan erişilebilirlik) veya türün kendisindeki bir bildirim tarafından gizlendiği için türetilmiş bir tür içinde erişilebilir olmayabilir (Devralma yoluyla gizleme).However, an inherited member may not be accessible in a derived type, either because of its declared accessibility (Declared accessibility) or because it is hidden by a declaration in the type itself (Hiding through inheritance).

Ad alanı üyeleriNamespace members

Kapsanan ad alanı olmayan ad alanları ve türler, genel ad alanının üyeleridir.Namespaces and types that have no enclosing namespace are members of the global namespace. Bu, doğrudan genel bildirim alanında belirtilen adlara karşılık gelir.This corresponds directly to the names declared in the global declaration space.

Ad alanı içinde belirtilen ad alanları ve türler, bu ad alanının üyeleridir.Namespaces and types declared within a namespace are members of that namespace. Bu, doğrudan ad alanının bildirim alanında belirtilen adlara karşılık gelir.This corresponds directly to the names declared in the declaration space of the namespace.

Ad alanlarının erişim kısıtlamaları yoktur.Namespaces have no access restrictions. Özel, korumalı veya iç ad alanları bildirmek mümkün değildir ve ad alanı adları her zaman herkese açıktır.It is not possible to declare private, protected, or internal namespaces, and namespace names are always publicly accessible.

Yapı üyeleriStruct members

Bir yapının üyeleri, yapı içinde ve yapının doğrudan temel sınıfından System.ValueType ve dolaylı temel sınıftan devralınan üyelerde belirtilen üyeleridir object .The members of a struct are the members declared in the struct and the members inherited from the struct's direct base class System.ValueType and the indirect base class object.

Basit bir türün üyeleri, basit türün diğer adı olan yapı türünün üyelerine karşılık gelir:The members of a simple type correspond directly to the members of the struct type aliased by the simple type:

  • Üyeleri sbyte System.SByte Yapı üyeleridir.The members of sbyte are the members of the System.SByte struct.
  • Üyeleri byte System.Byte Yapı üyeleridir.The members of byte are the members of the System.Byte struct.
  • Üyeleri short System.Int16 Yapı üyeleridir.The members of short are the members of the System.Int16 struct.
  • Üyeleri ushort System.UInt16 Yapı üyeleridir.The members of ushort are the members of the System.UInt16 struct.
  • Üyeleri int System.Int32 Yapı üyeleridir.The members of int are the members of the System.Int32 struct.
  • Üyeleri uint System.UInt32 Yapı üyeleridir.The members of uint are the members of the System.UInt32 struct.
  • Üyeleri long System.Int64 Yapı üyeleridir.The members of long are the members of the System.Int64 struct.
  • Üyeleri ulong System.UInt64 Yapı üyeleridir.The members of ulong are the members of the System.UInt64 struct.
  • Üyeleri char System.Char Yapı üyeleridir.The members of char are the members of the System.Char struct.
  • Üyeleri float System.Single Yapı üyeleridir.The members of float are the members of the System.Single struct.
  • Üyeleri double System.Double Yapı üyeleridir.The members of double are the members of the System.Double struct.
  • Üyeleri decimal System.Decimal Yapı üyeleridir.The members of decimal are the members of the System.Decimal struct.
  • Üyeleri bool System.Boolean Yapı üyeleridir.The members of bool are the members of the System.Boolean struct.

Listeleme üyeleriEnumeration members

Bir numaralandırmanın üyeleri numaralandırmada ve numaralandırmanın doğrudan temel sınıfından ve dolaylı temel sınıflardan devralınan üyelerde belirtilen sabitlerdir System.Enum System.ValueType object .The members of an enumeration are the constants declared in the enumeration and the members inherited from the enumeration's direct base class System.Enum and the indirect base classes System.ValueType and object.

Sınıf üyeleriClass members

Bir sınıfın üyeleri sınıfta ve temel sınıftan devralınan üyelere ( object temel sınıfı olmayan sınıf hariç) eklenir.The members of a class are the members declared in the class and the members inherited from the base class (except for class object which has no base class). Temel sınıftan devralınan Üyeler, taban sınıfının sabitler, alanları, yöntemleri, özellikleri, olayları, Dizin oluşturucular, işleçler ve türleri ve temel sınıfın statik oluşturucuları değil, temel sınıfın türlerini içerir.The members inherited from the base class include the constants, fields, methods, properties, events, indexers, operators, and types of the base class, but not the instance constructors, destructors and static constructors of the base class. Temel sınıf üyeleri, erişilebilirliğine göre devralınmaz.Base class members are inherited without regard to their accessibility.

Bir sınıf bildirimi, sabitler, alanlar, Yöntemler, özellikler, olaylar, Dizin oluşturucular, işleçler, örnek oluşturucular, Yıkıcılar, statik oluşturucular ve türler için bildirimler içerebilir.A class declaration may contain declarations of constants, fields, methods, properties, events, indexers, operators, instance constructors, destructors, static constructors and types.

Ve üyeleri, object string diğer adları olan sınıf türlerinin üyelerine doğrudan karşılık gelir:The members of object and string correspond directly to the members of the class types they alias:

  • Üyeleri, object System.Object sınıfının üyeleridir.The members of object are the members of the System.Object class.
  • Üyeleri, string System.String sınıfının üyeleridir.The members of string are the members of the System.String class.

Arabirim üyeleriInterface members

Bir arabirimin üyeleri, arabirimde ve arabirimin tüm temel arabirimlerinde belirtilen üyelerdir.The members of an interface are the members declared in the interface and in all base interfaces of the interface. Sınıftaki Üyeler, object hiçbir arabirimin (arabirim üyesi) üyesi değil, tamamen konuşuyor.The members in class object are not, strictly speaking, members of any interface (Interface members). Ancak, sınıfındaki Üyeler object herhangi bir arabirim türünde (üye arama) üye arama yoluyla kullanılabilir.However, the members in class object are available via member lookup in any interface type (Member lookup).

Dizi üyeleriArray members

Bir dizinin üyeleri sınıfından devralınan üyelerdir System.Array .The members of an array are the members inherited from class System.Array.

Temsilci üyeleriDelegate members

Bir temsilcinin üyeleri sınıfından devralınan üyelerdir System.Delegate .The members of a delegate are the members inherited from class System.Delegate.

Üye erişimiMember access

Üyelerin bildirimleri üye erişimi üzerinde denetime izin verir.Declarations of members allow control over member access. Bir üyenin erişilebilirliği, varsa, hemen kapsayan türün erişilebilirliği ile birleştirilmiş üyenin tanımlanmış erişilebilirliği (belirtilen erişilebilirlik) tarafından belirlenir.The accessibility of a member is established by the declared accessibility (Declared accessibility) of the member combined with the accessibility of the immediately containing type, if any.

Belirli bir üyeye erişime izin verildiğinde, üye *erişilebilir _ olarak kabul edilir.When access to a particular member is allowed, the member is said to be *accessible _. Buna karşılık, belirli bir üyeye erişime izin verilmediğinde üye _ erişilemeyen * olarak kabul edilir.Conversely, when access to a particular member is disallowed, the member is said to be _*inaccessible**. Bir üyeye erişim, erişimin gerçekleştiği metin konumu üyenin erişilebilirlik etki alanına (erişilebilirlik etki alanları) dahil edildiğinde izin verilir.Access to a member is permitted when the textual location in which the access takes place is included in the accessibility domain (Accessibility domains) of the member.

Tanımlanan erişilebilirlikDeclared accessibility

Bir üyenin tanımlanmış erişilebilirliği aşağıdakilerden biri olabilir:The declared accessibility of a member can be one of the following:

  • Public, üye bildiriminde bir değiştirici eklenerek seçilidir public .Public, which is selected by including a public modifier in the member declaration. ' Nin sezgisel anlamı public "erişim sınırlı değil" anlamına gelir.The intuitive meaning of public is "access not limited".
  • Korumalı, üye bildiriminde bir değiştirici eklenerek seçilir protected .Protected, which is selected by including a protected modifier in the member declaration. ' Nin sezgisel anlamı, protected "erişim, kapsayan sınıftan türetilmiş içeren sınıf veya türlerle sınırlı" olur.The intuitive meaning of protected is "access limited to the containing class or types derived from the containing class".
  • İç, üye bildiriminde bir değiştirici eklenerek seçilir internal .Internal, which is selected by including an internal modifier in the member declaration. Öğesinin sezgisel anlamı internal "Bu programla sınırlı erişim" dir.The intuitive meaning of internal is "access limited to this program".
  • Üye bildiriminde hem a hem de değiştirici dahil tarafından seçilen, korunan dahili (yani protected veya internal) protected internal .Protected internal (meaning protected or internal), which is selected by including both a protected and an internal modifier in the member declaration. ' Nin sezgisel anlamı, protected internal "Bu program ile sınırlı erişim veya içeren sınıftan türetilmiş türler" anlamına gelir.The intuitive meaning of protected internal is "access limited to this program or types derived from the containing class".
  • Özel, üye bildiriminde bir değiştirici eklenerek seçilir private .Private, which is selected by including a private modifier in the member declaration. ' Nin sezgisel anlamı private ", kapsayan türle sınırlı" anlamına gelir.The intuitive meaning of private is "access limited to the containing type".

Bir üye bildiriminin gerçekleştiği içeriğe bağlı olarak, yalnızca belirli bir tanımlı erişilebilirlik türlerine izin verilir.Depending on the context in which a member declaration takes place, only certain types of declared accessibility are permitted. Ayrıca, bir üye bildirimi herhangi bir erişim değiştiricisi içermiyorsa, bildirimin gerçekleştiği bağlam, varsayılan olarak belirtilen erişilebilirliği belirler.Furthermore, when a member declaration does not include any access modifiers, the context in which the declaration takes place determines the default declared accessibility.

  • Ad alanları örtük olarak public erişilebilirliği bildirdi.Namespaces implicitly have public declared accessibility. Ad alanı bildirimlerinde erişim değiştiricilerine izin verilmez.No access modifiers are allowed on namespace declarations.
  • Derleme birimleri veya ad alanlarında belirtilen türler, public internal Erişilebilirlik ve varsayılan olarak tanımlanmış erişilebilirliği içerebilir veya bunları belirtebilir internal .Types declared in compilation units or namespaces can have public or internal declared accessibility and default to internal declared accessibility.
  • Sınıf üyeleri, belirtilen beş tür erişilebilirliği ve varsayılan olarak private tanımlanmış erişilebilirliği içerebilir.Class members can have any of the five kinds of declared accessibility and default to private declared accessibility. (Bir sınıfın üyesi olarak belirtilen bir türün beş tür tanımlanmış erişilebilirliği olabileceğini, ancak bir ad alanının üyesi olarak bildirildiği bir türün yalnızca public veya internal tanımlanmış erişilebilirliği olabilir.)(Note that a type declared as a member of a class can have any of the five kinds of declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • public internal private Yapılar örtük olarak mühürlendikleri için yapı üyeleri, erişilebilirliği ve varsayılan olarak private tanımlanmış erişilebilirliği içerebilir.Struct members can have public, internal, or private declared accessibility and default to private declared accessibility because structs are implicitly sealed. Bir yapıda tanıtılan yapı üyeleri (yani, bu yapı tarafından devralınmaz) protected erişilebilirliği içeremez veya protected internal bildirilemez.Struct members introduced in a struct (that is, not inherited by that struct) cannot have protected or protected internal declared accessibility. (Bir yapının üyesi olarak belirtilen bir türün erişilebilirliği olabileceğini, public internal veya private bildirdiğini unutmayın, bir ad alanının üyesi olarak bildirildiği bir tür yalnızca public veya internal tanımlanmış erişilebilirliği olabilir.)(Note that a type declared as a member of a struct can have public, internal, or private declared accessibility, whereas a type declared as a member of a namespace can have only public or internal declared accessibility.)
  • Arabirim üyeleri örtülü olarak public erişilebilirliği bildirdi.Interface members implicitly have public declared accessibility. Arabirim üye bildirimlerinde erişim değiştiricilerine izin verilmez.No access modifiers are allowed on interface member declarations.
  • Numaralandırma üyeleri örtülü olarak public erişilebilirliği bildirdi.Enumeration members implicitly have public declared accessibility. Numaralandırma üye bildirimlerinde erişim değiştiricilerine izin verilmez.No access modifiers are allowed on enumeration member declarations.

Erişilebilirlik etki alanlarıAccessibility domains

Üyenin *erişilebilirlik etki alanı _, üyeye erişime izin verilen program metninin (muhtemelen ayrık) bölümlerinden oluşur.The *accessibility domain _ of a member consists of the (possibly disjoint) sections of program text in which access to the member is permitted. Bir üyenin erişilebilirlik etki alanını tanımlama amacıyla bir üyenin bir tür içinde bildirilmemiş olması ve bir üyenin başka bir tür içinde bildirildiği durumlarda iç içe olduğu söylenir.For purposes of defining the accessibility domain of a member, a member is said to be top-level if it is not declared within a type, and a member is said to be nested if it is declared within another type. Ayrıca, bir programın Program metni , programın tüm kaynak dosyalarında bulunan tüm program metinleri olarak tanımlanır ve bir türün program metni, bu türün (büyük olasılıkla tür içinde iç içe geçmiş türler dahil olmak üzere) _type_declaration * öğeleri içinde bulunan tüm program metinleri olarak tanımlanır.Furthermore, the program text of a program is defined as all program text contained in all source files of the program, and the program text of a type is defined as all program text contained in the _type_declaration*s of that type (including, possibly, types that are nested within the type).

Önceden tanımlanmış bir türün erişilebilirlik etki alanı (örneğin object , int veya double ) sınırsızdır.The accessibility domain of a predefined type (such as object, int, or double) is unlimited.

Bir programda belirtilen üst düzey ilişkisiz türdeki T (bağlı ve ilişkisiz türler) erişilebilirlik etki alanı P aşağıdaki gibi tanımlanır:The accessibility domain of a top-level unbound type T (Bound and unbound types) that is declared in a program P is defined as follows:

  • ' Nin belirtilen erişilebilirliği T ise public , öğesinin erişilebilirlik etki alanı, ' T ın program metni P ve başvurduğu herhangi bir programdır P .If the declared accessibility of T is public, the accessibility domain of T is the program text of P and any program that references P.
  • ' Nin belirtilen erişilebilirliği T ise internal , öğesinin erişilebilirlik etki alanı T öğesinin program metni olur P .If the declared accessibility of T is internal, the accessibility domain of T is the program text of P.

Bu tanımlardan, üst düzey ilişkisiz türdeki erişilebilirlik etki alanının her zaman en azından bu türün bildirildiği programın program metni olduğunu takip eder.From these definitions it follows that the accessibility domain of a top-level unbound type is always at least the program text of the program in which that type is declared.

Oluşturulmuş bir tür için erişilebilirlik etki alanı, T<A1, ..., An> ilişkisiz genel türdeki erişilebilirlik etki alanının T ve tür bağımsız değişkenlerinin erişilebilirlik etki alanlarının kesişimidir A1, ..., An .The accessibility domain for a constructed type T<A1, ..., An> is the intersection of the accessibility domain of the unbound generic type T and the accessibility domains of the type arguments A1, ..., An.

Bir program içindeki bir tür içinde bildirildiği iç içe bir üyenin erişilebilirlik etki alanı, M T P aşağıdaki gibi tanımlanır (bunun M büyük olasılıkla bir tür olabileceğini unutmayın):The accessibility domain of a nested member M declared in a type T within a program P is defined as follows (noting that M itself may possibly be a type):

  • ' Nin belirtilen erişilebilirliği ise, öğesinin erişilebilirlik etki alanıdır M public M T .If the declared accessibility of M is public, the accessibility domain of M is the accessibility domain of T.
  • ' Nin belirtilen erişilebilirliği M ise protected internal , D öğesinin program metninin birleşimi P ve öğesinden türetilen herhangi bir türün program metni, dışında bir şekilde T bildirilmiştir P .If the declared accessibility of M is protected internal, let D be the union of the program text of P and the program text of any type derived from T, which is declared outside P. ' Nin erişilebilirlik etki alanı, M ile erişilebilirlik etki alanının kesişimidir T D .The accessibility domain of M is the intersection of the accessibility domain of T with D.
  • ' Nin belirtilen erişilebilirliği M ise protected , D öğesinin program metninin birleşimi T ve öğesinden türetilen herhangi bir türün program metni olur T .If the declared accessibility of M is protected, let D be the union of the program text of T and the program text of any type derived from T. ' Nin erişilebilirlik etki alanı, M ile erişilebilirlik etki alanının kesişimidir T D .The accessibility domain of M is the intersection of the accessibility domain of T with D.
  • ' Nin belirtilen erişilebilirliği M ise internal , öğesinin erişilebilirlik etki alanı, ' ın ' ın M erişilebilirlik etki alanının kesişimidir T P .If the declared accessibility of M is internal, the accessibility domain of M is the intersection of the accessibility domain of T with the program text of P.
  • ' Nin belirtilen erişilebilirliği M ise private , öğesinin erişilebilirlik etki alanı M öğesinin program metni olur T .If the declared accessibility of M is private, the accessibility domain of M is the program text of T.

Bu tanımlardan, iç içe bir üyenin erişilebilirlik etki alanının her zaman en azından üyenin bildirildiği türdeki program metni olduğunu takip eder.From these definitions it follows that the accessibility domain of a nested member is always at least the program text of the type in which the member is declared. Ayrıca, bir üyenin erişilebilirlik etki alanının, üyenin bildirildiği türün erişilebilirlik etki alanından daha da hiç olmadığı anlamına gelir.Furthermore, it follows that the accessibility domain of a member is never more inclusive than the accessibility domain of the type in which the member is declared.

Sezgisel koşullarda, bir tür veya üyeye M erişildiğinde, erişime izin verildiğinden emin olmak için aşağıdaki adımlar değerlendirilir:In intuitive terms, when a type or member M is accessed, the following steps are evaluated to ensure that the access is permitted:

  • İlk olarak, M bir tür içinde (bir derleme birimi veya bir ad alanı aksine) bildirilirse, bu tür erişilebilir değilse bir derleme zamanı hatası oluşur.First, if M is declared within a type (as opposed to a compilation unit or a namespace), a compile-time error occurs if that type is not accessible.
  • , İse, M public erişime izin verilir.Then, if M is public, the access is permitted.
  • Aksi takdirde, ise, ' nin M protected internal bildirildiği programda meydana gelirse M veya içinde bildirildiği sınıftan türetilmiş bir sınıf içinde meydana gelirse veya M türetilmiş sınıf türü (Örneğin, korumalı erişim) tarafından gerçekleştiği durumlarda erişime izin verilir.Otherwise, if M is protected internal, the access is permitted if it occurs within the program in which M is declared, or if it occurs within a class derived from the class in which M is declared and takes place through the derived class type (Protected access for instance members).
  • Aksi takdirde, M ise, ' protected ın bildirildiği sınıf içinde meydana gelirse M veya içinde bildirildiği sınıftan türetilmiş bir sınıf içinde meydana gelirse veya M türetilmiş sınıf türü (Örneğin, korumalı erişim) tarafından gerçekleşmişse erişime izin verilir.Otherwise, if M is protected, the access is permitted if it occurs within the class in which M is declared, or if it occurs within a class derived from the class in which M is declared and takes place through the derived class type (Protected access for instance members).
  • Aksi takdirde, M ise, internal içinde bildirildiği programın içinde meydana gelirse erişime izin verilir M .Otherwise, if M is internal, the access is permitted if it occurs within the program in which M is declared.
  • Aksi takdirde, M ise, ' private ın bildirildiği tür içinde oluşması durumunda erişime izin verilir M .Otherwise, if M is private, the access is permitted if it occurs within the type in which M is declared.
  • Aksi takdirde, tür veya üyeye erişilemez ve derleme zamanı hatası oluşur.Otherwise, the type or member is inaccessible, and a compile-time error occurs.

ÖrnekteIn the example

public class A
{
    public static int X;
    internal static int Y;
    private static int Z;
}

internal class B
{
    public static int X;
    internal static int Y;
    private static int Z;

    public class C
    {
        public static int X;
        internal static int Y;
        private static int Z;
    }

    private class D
    {
        public static int X;
        internal static int Y;
        private static int Z;
    }
}

sınıflar ve Üyeler aşağıdaki erişilebilirlik etki alanlarına sahiptir:the classes and members have the following accessibility domains:

  • Ve erişilebilirlik etki alanı A A.X sınırsızdır.The accessibility domain of A and A.X is unlimited.
  • ,,,,, Ve ' nin erişilebilirlik etki alanı, A.Y B B.X B.Y B.C B.C.X B.C.Y içeren programın program metni.The accessibility domain of A.Y, B, B.X, B.Y, B.C, B.C.X, and B.C.Y is the program text of the containing program.
  • Öğesinin erişilebilirlik etki alanı, A.Z öğesinin program metni A .The accessibility domain of A.Z is the program text of A.
  • Ve ' ın erişilebilirlik etki alanı, B.Z B.D B ve ' ın program metni de dahil olmak üzere, öğesinin program metindir B.C B.D .The accessibility domain of B.Z and B.D is the program text of B, including the program text of B.C and B.D.
  • Öğesinin erişilebilirlik etki alanı, B.C.Z öğesinin program metni B.C .The accessibility domain of B.C.Z is the program text of B.C.
  • Ve ' ın erişilebilirlik etki alanı, B.D.X B.D.Y B ve ' ın program metni de dahil olmak üzere, öğesinin program metindir B.C B.D .The accessibility domain of B.D.X and B.D.Y is the program text of B, including the program text of B.C and B.D.
  • Öğesinin erişilebilirlik etki alanı, B.D.Z öğesinin program metni B.D .The accessibility domain of B.D.Z is the program text of B.D.

Örnekte gösterildiği gibi, bir üyenin erişilebilirlik etki alanı, kapsayan türden hiçbir şekilde daha büyük değildir.As the example illustrates, the accessibility domain of a member is never larger than that of a containing type. Örneğin, tüm X üyelerin ortak olarak tanımlanmış erişilebilirliği olsa da, hepsi, A.X kapsayan bir tür tarafından kısıtlanan erişilebilirlik etki alanlarına sahiptir.For example, even though all X members have public declared accessibility, all but A.X have accessibility domains that are constrained by a containing type.

Üyelerbölümünde açıklandığı gibi, bir temel sınıfın, örnek oluşturucular, Yıkıcılar ve statik oluşturucular hariç tüm üyeleri türetilmiş türler tarafından devralınır.As described in Members, all members of a base class, except for instance constructors, destructors and static constructors, are inherited by derived types. Bu, bir temel sınıfın hatta özel üyelerini içerir.This includes even private members of a base class. Ancak, özel bir üyenin erişilebilirlik etki alanı yalnızca üyenin bildirildiği türün program metnini içerir.However, the accessibility domain of a private member includes only the program text of the type in which the member is declared. ÖrnekteIn the example

class A
{
    int x;

    static void F(B b) {
        b.x = 1;        // Ok
    }
}

class B: A
{
    static void F(B b) {
        b.x = 1;        // Error, x not accessible
    }
}

Bsınıfı, sınıfından özel üyeyi devralır x A .the B class inherits the private member x from the A class. Üye özel olduğundan, yalnızca class_body içinde erişilebilir A .Because the member is private, it is only accessible within the class_body of A. Bu nedenle, b.x yöntemde başarılı olma erişimi A.F , ancak yönteminde başarısız olur B.F .Thus, the access to b.x succeeds in the A.F method, but fails in the B.F method.

Örnek üyeleri için korumalı erişimProtected access for instance members

Bir protected örnek üyesine, bildirildiği sınıfın program metni dışında erişildiğinde ve bir protected internal örnek üyeye bildirildiği programın program metni dışında erişildiğinde, erişim, bildirildiği sınıftan türetilen bir sınıf bildiriminde gerçekleşmelidir, bu da erişim bir sınıf bildirimi içinde yer almalıdır.When a protected instance member is accessed outside the program text of the class in which it is declared, and when a protected internal instance member is accessed outside the program text of the program in which it is declared, the access must take place within a class declaration that derives from the class in which it is declared. Ayrıca, bu türetilmiş sınıf türünün bir örneği veya ondan oluşturulan bir sınıf türü üzerinden gerçekleşmesi için erişim gerekir.Furthermore, the access is required to take place through an instance of that derived class type or a class type constructed from it. Bu kısıtlama, bir türetilen sınıfın, Üyeler aynı temel sınıftan devralınsa bile, diğer türetilmiş sınıfların korunan üyelerine erişmesini önler.This restriction prevents one derived class from accessing protected members of other derived classes, even when the members are inherited from the same base class.

BKorumalı örnek üyesini bildiren M ve D öğesinden türetilen bir sınıf olmasına izin veren bir temel sınıf sağlar B .Let B be a base class that declares a protected instance member M, and let D be a class that derives from B. Class_body içinde D , erişimi M aşağıdaki formlardan birini gerçekleştirebilir:Within the class_body of D, access to M can take one of the following forms:

  • Formun nitelenmemiş bir type_name veya primary_expression M .An unqualified type_name or primary_expression of the form M.
  • Türü veya öğesinden türetilmiş bir sınıf olan, bu formun primary_expression , E.M E T T T sınıf türü D veya tarafından oluşturulan bir sınıf türü DA primary_expression of the form E.M, provided the type of E is T or a class derived from T, where T is the class type D, or a class type constructed from D
  • Formun primary_expression base.M .A primary_expression of the form base.M.

Bu erişim formlarına ek olarak, türetilmiş bir sınıf bir constructor_initializer (Oluşturucu başlatıcıları) bir temel sınıfın korumalı örnek oluşturucusuna erişebilir.In addition to these forms of access, a derived class can access a protected instance constructor of a base class in a constructor_initializer (Constructor initializers).

ÖrnekteIn the example

public class A
{
    protected int x;

    static void F(A a, B b) {
        a.x = 1;        // Ok
        b.x = 1;        // Ok
    }
}

public class B: A
{
    static void F(A a, B b) {
        a.x = 1;        // Error, must access through instance of B
        b.x = 1;        // Ok
    }
}

A' de, x A B erişimin bir örneği A veya öğesinden türetilmiş bir sınıf aracılığıyla gerçekleştiği durumlar nedeniyle, ' ın ve ' nin örnekleri üzerinden erişmek mümkündür A .within A, it is possible to access x through instances of both A and B, since in either case the access takes place through an instance of A or a class derived from A. Bununla birlikte, içinde türetilmediği için ' de B x bir örneği üzerinden erişim mümkün değildir A A B .However, within B, it is not possible to access x through an instance of A, since A does not derive from B.

ÖrnekteIn the example

class C<T>
{
    protected T x;
}

class D<T>: C<T>
{
    static void F() {
        D<T> dt = new D<T>();
        D<int> di = new D<int>();
        D<string> ds = new D<string>();
        dt.x = default(T);
        di.x = 123;
        ds.x = "test";
    }
}

' a yönelik üç atama, x hepsi genel türden oluşturulan sınıf türleri örnekleri aracılığıyla gerçekleştiğinden izin verilir.the three assignments to x are permitted because they all take place through instances of class types constructed from the generic type.

Erişilebilirlik kısıtlamalarıAccessibility constraints

C# dilinde bazı yapılar, bir türün en azından üye veya başka bir tür olarak erişilebilir olmasını gerektirir.Several constructs in the C# language require a type to be at least as accessible as a member or another type. Bir tür, öğesinin erişilebilirlik etki alanının, ' nin T M T erişilebilirlik etki alanının bir üst kümesi olması halinde en az bir üye veya tür olarak erişilebilir olarak kabul edilir M .A type T is said to be at least as accessible as a member or type M if the accessibility domain of T is a superset of the accessibility domain of M. Diğer bir deyişle, T M T erişilebilen tüm bağlamlarda erişilebilir olduğu gibi en az erişilebilir olur M .In other words, T is at least as accessible as M if T is accessible in all contexts in which M is accessible.

Aşağıdaki erişilebilirlik kısıtlamaları vardır:The following accessibility constraints exist:

  • Bir sınıf türünün doğrudan temel sınıfı en azından sınıf türünün kendisi kadar erişilebilir olmalıdır.The direct base class of a class type must be at least as accessible as the class type itself.
  • Arabirim türünün açık temel arabirimleri en az arabirim türünün kendisi kadar erişilebilir olmalıdır.The explicit base interfaces of an interface type must be at least as accessible as the interface type itself.
  • Bir temsilci türünün dönüş türü ve parametre türleri en azından temsilci türünün kendisi kadar erişilebilir olmalıdır.The return type and parameter types of a delegate type must be at least as accessible as the delegate type itself.
  • Bir sabit türü en az sabit değer olarak erişilebilir olmalıdır.The type of a constant must be at least as accessible as the constant itself.
  • Alanın türü en azından alanın kendisi kadar erişilebilir olmalıdır.The type of a field must be at least as accessible as the field itself.
  • Bir yöntemin dönüş türü ve parametre türleri en az yöntemin kendisi olarak erişilebilir olmalıdır.The return type and parameter types of a method must be at least as accessible as the method itself.
  • Özelliğin türü en az özelliğin kendisi olarak erişilebilir olmalıdır.The type of a property must be at least as accessible as the property itself.
  • Bir olayın türü en az olayın kendisi olarak erişilebilir olmalıdır.The type of an event must be at least as accessible as the event itself.
  • Bir dizin oluşturucunun türü ve parametre türleri en azından dizin oluşturucunun kendisi olarak erişilebilir olmalıdır.The type and parameter types of an indexer must be at least as accessible as the indexer itself.
  • Bir işlecin dönüş türü ve parametre türleri en az işlecin kendisi olarak erişilebilir olmalıdır.The return type and parameter types of an operator must be at least as accessible as the operator itself.
  • Örnek oluşturucusunun parametre türleri en azından örnek oluşturucusunun kendisi kadar erişilebilir olmalıdır.The parameter types of an instance constructor must be at least as accessible as the instance constructor itself.

ÖrnekteIn the example

class A {...}

public class B: A {...}

Ben az olarak erişilebilir olmadığı için sınıf, derleme zamanı hatasına neden A olur B .the B class results in a compile-time error because A is not at least as accessible as B.

Benzer şekilde, örnekteLikewise, in the example

class A {...}

public class B
{
    A F() {...}

    internal A G() {...}

    public A H() {...}
}

H B dönüş türü A en az Yöntem olarak erişilebilir olmadığından, içindeki yöntemi bir derleme zamanı hatası ile sonuçlanır.the H method in B results in a compile-time error because the return type A is not at least as accessible as the method.

İmzalar ve aşırı yüklemeSignatures and overloading

Yöntemler, örnek oluşturucular, Dizin oluşturucular ve işleçler, imzalarına göre belirlenir:Methods, instance constructors, indexers, and operators are characterized by their signatures:

  • Bir yöntemin imzası, yöntemin adından, tür parametrelerinin sayısına ve her bir biçimsel parametrenin her birinin tür ve türü (değer, başvuru veya çıkış) soldan sağa doğru olarak değerlendirilir.The signature of a method consists of the name of the method, the number of type parameters and the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. Bu amaçlar için, bir biçimsel parametre türünde oluşan yöntemin tür parametresi, kendi adı tarafından değil, yönteminin tür bağımsız değişkeni listesindeki sıra konumuna göre tanımlanır.For these purposes, any type parameter of the method that occurs in the type of a formal parameter is identified not by its name, but by its ordinal position in the type argument list of the method. Yöntemin imzası, dönüş türünü, params en sağdaki parametre için belirtilemeyen değiştirici veya isteğe bağlı tür parametresi kısıtlamalarını içermez.The signature of a method specifically does not include the return type, the params modifier that may be specified for the right-most parameter, nor the optional type parameter constraints.
  • Bir örnek oluşturucusunun imzası, her bir biçimsel parametrenin türü ve türü (değer, başvuru veya çıkış), soldan sağa doğru olarak değerlendirilir.The signature of an instance constructor consists of the type and kind (value, reference, or output) of each of its formal parameters, considered in the order left to right. Özellikle bir örnek oluşturucusunun imzası, params en sağdaki parametre için belirtilemeyen değiştirici içermez.The signature of an instance constructor specifically does not include the params modifier that may be specified for the right-most parameter.
  • Bir dizin oluşturucunun imzası, soldan sağa doğru olarak kabul edilen her bir biçimsel parametre türünden oluşur.The signature of an indexer consists of the type of each of its formal parameters, considered in the order left to right. Bir dizin oluşturucunun imzası özellikle öğe türünü içermez veya params en sağdaki parametre için belirtime değiştiricisini de içermez.The signature of an indexer specifically does not include the element type, nor does it include the params modifier that may be specified for the right-most parameter.
  • Bir işlecin imzası, işlecin adından ve her bir biçimsel parametrelerinin, soldan sağa doğru olarak kabul edilen türünden oluşur.The signature of an operator consists of the name of the operator and the type of each of its formal parameters, considered in the order left to right. Bir işlecin imzası özellikle sonuç türünü içermez.The signature of an operator specifically does not include the result type.

İmzalar, sınıflarda, yapılarda ve arabirimlerde üyelerin aşırı yüklenmesine yönelik etkinleştirme mekanizmasıdır:Signatures are the enabling mechanism for overloading of members in classes, structs, and interfaces:

  • Yöntemlerin aşırı yüklemesi, bir sınıf, yapı veya arabirimin aynı ada sahip birden çok yöntem bildirmesine izin verdiğinden, imzaları bu sınıf, yapı veya arabirim içinde benzersizdir.Overloading of methods permits a class, struct, or interface to declare multiple methods with the same name, provided their signatures are unique within that class, struct, or interface.
  • Örnek oluşturucuların aşırı yüklenmesi, bir sınıfın veya yapının birden çok örnek Oluşturucu tanımlamasına izin verdiğinden, imzaları bu sınıf veya yapı içinde benzersiz olarak belirtilmelidir.Overloading of instance constructors permits a class or struct to declare multiple instance constructors, provided their signatures are unique within that class or struct.
  • Dizin oluşturucularının aşırı yüklemesi, bir sınıf, yapı veya arabirimin birden çok dizin oluşturma kullanılmasına izin verir, ancak imzaları bu sınıf, yapı veya arabirim içinde benzersizdir.Overloading of indexers permits a class, struct, or interface to declare multiple indexers, provided their signatures are unique within that class, struct, or interface.
  • İşleçlerin aşırı yüklemesi, bir sınıf veya yapının aynı ada sahip birden çok işleç tanımlamasına izin verdiğinden, imzaları bu sınıf veya yapı içinde benzersizdir.Overloading of operators permits a class or struct to declare multiple operators with the same name, provided their signatures are unique within that class or struct.

outVe ref parametre değiştiricileri bir imzanın parçası olarak kabul edilse de, tek bir türde belirtilen Üyeler yalnızca ve ile imzasında farklı olamaz ref out .Although out and ref parameter modifiers are considered part of a signature, members declared in a single type cannot differ in signature solely by ref and out. İki üye, her iki yöntemde de değiştiricilerin her ikisi de out değiştiriciler olarak değiştirilmişse aynı türde olan imzalara sahip aynı türde bir derleme zamanı hatası oluşur ref .A compile-time error occurs if two members are declared in the same type with signatures that would be the same if all parameters in both methods with out modifiers were changed to ref modifiers. İmza eşleştirmesinin diğer amaçları (örn. gizleme veya geçersiz kılma) için ref ve out imzanın bir parçası olarak kabul edilir ve birbirleriyle eşleşmez.For other purposes of signature matching (e.g., hiding or overriding), ref and out are considered part of the signature and do not match each other. (Bu kısıtlama, C# programlarının, yalnızca ve ' de farklı yöntemler tanımlamak için bir yol sağlamayan ortak dil altyapısında (CLı) çalışmak üzere kolayca çevrilmesine izin versağlamaktır ref out .)(This restriction is to allow C#  programs to be easily translated to run on the Common Language Infrastructure (CLI), which does not provide a way to define methods that differ solely in ref and out.)

İmzaların amaçları doğrultusunda türler object ve dynamic aynı olarak değerlendirilir.For the purposes of signatures, the types object and dynamic are considered the same. Bu nedenle, tek bir türde belirtilen Üyeler yalnızca ve ile imzasında farklı değildir object dynamic .Members declared in a single type can therefore not differ in signature solely by object and dynamic.

Aşağıdaki örnek, imzaları ile birlikte aşırı yüklenmiş yöntem bildirimlerinin bir kümesini gösterir.The following example shows a set of overloaded method declarations along with their signatures.

interface ITest
{
    void F();                        // F()

    void F(int x);                   // F(int)

    void F(ref int x);               // F(ref int)

    void F(out int x);               // F(out int)      error

    void F(int x, int y);            // F(int, int)

    int F(string s);                 // F(string)

    int F(int x);                    // F(int)          error

    void F(string[] a);              // F(string[])

    void F(params string[] a);       // F(string[])     error
}

Any ref ve out parametre değiştiricilerin (Yöntem parametreleri) bir imzanın parçası olduğunu unutmayın.Note that any ref and out parameter modifiers (Method parameters) are part of a signature. Bu nedenle, F(int) ve F(ref int) benzersiz imzalardır.Thus, F(int) and F(ref int) are unique signatures. Ancak, F(ref int) F(out int) imzaları yalnızca ve ile farklı olduğundan aynı arabirim içinde bildirilemez ref out .However, F(ref int) and F(out int) cannot be declared within the same interface because their signatures differ solely by ref and out. Ayrıca, dönüş türü ve params değiştiricinin bir imzanın parçası olmadığına ve bu nedenle yalnızca dönüş türüne göre veya değiştiricinin dahil edilmesi veya dışlamasına göre aşırı yüklenmesi mümkün değildir params .Also, note that the return type and the params modifier are not part of a signature, so it is not possible to overload solely based on return type or on the inclusion or exclusion of the params modifier. Bu nedenle, yöntemlerin bildirimleri F(int) ve F(params string[]) yukarıda belirtilen bildirimler derleme zamanı hatası ile sonuçlanır.As such, the declarations of the methods F(int) and F(params string[]) identified above result in a compile-time error.

KapsamlarScopes

Bir adın *scope _ ' i, ad nitelemeden ad tarafından belirtilen varlığa başvuruda bulunmak mümkün olduğu program metninin bölgesidir.The *scope _ of a name is the region of program text within which it is possible to refer to the entity declared by the name without qualification of the name. Kapsamlar iç içe olabilir ve bir iç kapsam bir dış kapsamdan bir adın anlamını yeniden bildirebilir (ancak, iç içe geçmiş bir blok içindeki bildirimlerin uyguladığı kısıtlamayı kaldırır, kapsayan bir blok içinde yerel bir değişkenle aynı ada sahip yerel bir değişken bildirmek mümkün değildir).Scopes can be nested, and an inner scope may redeclare the meaning of a name from an outer scope (this does not, however, remove the restriction imposed by Declarations that within a nested block it is not possible to declare a local variable with the same name as a local variable in an enclosing block). Daha sonra dış kapsamdaki ad, iç kapsamın kapsadığı program metni bölgesinde _ Hidden* olarak belirlenir ve dış ada erişim yalnızca adı niteleyerek mümkündür.The name from the outer scope is then said to be _ hidden* in the region of program text covered by the inner scope, and access to the outer name is only possible by qualifying the name.

  • Kapsayan namespace_declaration olmayan bir namespace_member_declaration (ad alanı üyeleri) tarafından belirtilen bir ad alanı üyesinin kapsamı, tüm program metindir.The scope of a namespace member declared by a namespace_member_declaration (Namespace members) with no enclosing namespace_declaration is the entire program text.
  • Tam adı olan bir namespace_declaration içinde namespace_member_declaration tarafından belirtilen bir ad alanı üyesinin kapsamı N , tam adı olan veya ile başlayan her namespace_declaration N N , ardından bir nokta gelen namespace_body.The scope of a namespace member declared by a namespace_member_declaration within a namespace_declaration whose fully qualified name is N is the namespace_body of every namespace_declaration whose fully qualified name is N or starts with N, followed by a period.
  • Bir extern_alias_directive tarafından tanımlanan ad kapsamı, derleme birimi veya ad alanı gövdesinin hemen içerdiği using_directive s, global_attributes ve namespace_member_declaration göre genişletilir.The scope of name defined by an extern_alias_directive extends over the using_directive s, global_attributes and namespace_member_declaration s of its immediately containing compilation unit or namespace body. Extern_alias_directive , temel alınan bildirim alanına yeni üye katkıda bulunmaz.An extern_alias_directive does not contribute any new members to the underlying declaration space. Diğer bir deyişle, extern_alias_directive geçişli değildir, ancak bunun yerine yalnızca, oluştuğu derleme birimini veya ad alanı gövdesini etkiler.In other words, an extern_alias_directive is not transitive, but, rather, affects only the compilation unit or namespace body in which it occurs.
  • Using_directive tarafından tanımlanan veya içeri aktarılan bir adın kapsamı (yönergeler kullanılarak), using_directive gerçekleştiği compilation_unit veya namespace_body namespace_member_declaration üzerinde uzanır.The scope of a name defined or imported by a using_directive (Using directives) extends over the namespace_member_declaration s of the compilation_unit or namespace_body in which the using_directive occurs. Using_directive , belirli bir compilation_unit veya namespace_body içinde kullanılabilir bir veya daha fazla ad alanı, tür veya üye adı oluşturabilir, ancak temel alınan bildirim alanına yeni üye katkıda bulunmaz.A using_directive may make zero or more namespace, type or member names available within a particular compilation_unit or namespace_body, but does not contribute any new members to the underlying declaration space. Diğer bir deyişle, using_directive geçişli değildir ancak bunun yerine yalnızca compilation_unit veya namespace_body etkiler.In other words, a using_directive is not transitive but rather affects only the compilation_unit or namespace_body in which it occurs.
  • Bir class_declaration (sınıf bildirimleri) type_parameter_list tarafından belirtilen bir tür parametresinin kapsamı, class_body class_base, type_parameter_constraints_clause s ve class_declaration .The scope of a type parameter declared by a type_parameter_list on a class_declaration (Class declarations) is the class_base, type_parameter_constraints_clause s, and class_body of that class_declaration.
  • Bir struct_declaration (struct bildirimleri) type_parameter_list tarafından belirtilen bir tür parametresinin kapsamı, bu struct_body struct_interfaces, type_parameter_constraints_clause s ve struct_declaration .The scope of a type parameter declared by a type_parameter_list on a struct_declaration (Struct declarations) is the struct_interfaces, type_parameter_constraints_clause s, and struct_body of that struct_declaration.
  • Bir interface_declaration (arabirim bildirimleri) type_parameter_list tarafından belirtilen bir tür parametresinin kapsamı, interface_body interface_base, type_parameter_constraints_clause s ve interface_declaration .The scope of a type parameter declared by a type_parameter_list on an interface_declaration (Interface declarations) is the interface_base, type_parameter_constraints_clause s, and interface_body of that interface_declaration.
  • Bir delegate_declaration (temsilci bildirimleri) type_parameter_list tarafından belirtilen bir tür parametresinin kapsamı, type_parameter_constraints_clause return_type, formal_parameter_list ve delegate_declaration.The scope of a type parameter declared by a type_parameter_list on a delegate_declaration (Delegate declarations) is the return_type, formal_parameter_list, and type_parameter_constraints_clause s of that delegate_declaration.
  • Bir class_member_declaration (sınıf gövdesi) tarafından belirtilen üyenin kapsamı, bildirimin gerçekleştiği class_body .The scope of a member declared by a class_member_declaration (Class body) is the class_body in which the declaration occurs. Ayrıca, bir sınıf üyesinin kapsamı, üyenin erişilebilirlik etki alanına (erişilebilirlik etki alanları) dahil edilen türetilmiş sınıfların class_body genişletir.In addition, the scope of a class member extends to the class_body of those derived classes that are included in the accessibility domain (Accessibility domains) of the member.
  • Bir struct_member_declaration (Yapı üyeleri) tarafından belirtilen bir üyenin kapsamı, bildirimin gerçekleştiği struct_body .The scope of a member declared by a struct_member_declaration (Struct members) is the struct_body in which the declaration occurs.
  • Bir enum_member_declaration (enum üyeleri) tarafından belirtilen bir üyenin kapsamı, bildirimin gerçekleştiği enum_body .The scope of a member declared by an enum_member_declaration (Enum members) is the enum_body in which the declaration occurs.
  • Bir method_declaration (metotlar) içinde belirtilen parametrenin kapsamı, bu method_declaration method_body .The scope of a parameter declared in a method_declaration (Methods) is the method_body of that method_declaration.
  • Bir indexer_declaration (Dizin oluşturucular) içinde belirtilen parametrenin kapsamı, bu indexer_declaration accessor_declarations .The scope of a parameter declared in an indexer_declaration (Indexers) is the accessor_declarations of that indexer_declaration.
  • Bir operator_declaration (işleçler) içinde belirtilen bir parametre kapsamı, bu operator_declaration bloğudur .The scope of a parameter declared in an operator_declaration (Operators) is the block of that operator_declaration.
  • Bir constructor_declaration (örnek oluşturucular) içinde belirtilen parametrenin kapsamı, bu constructor_declaration constructor_initializer ve bloğudur .The scope of a parameter declared in a constructor_declaration (Instance constructors) is the constructor_initializer and block of that constructor_declaration.
  • Bir lambda_expression (anonim işlev ifadeleri) içinde belirtilen bir parametre kapsamı, bu lambda_expression anonymous_function_bodyThe scope of a parameter declared in a lambda_expression (Anonymous function expressions) is the anonymous_function_body of that lambda_expression
  • Bir anonymous_method_expression (anonim işlev ifadeleri) içinde belirtilen bir parametre kapsamı, bu anonymous_method_expression bloğudur .The scope of a parameter declared in an anonymous_method_expression (Anonymous function expressions) is the block of that anonymous_method_expression.
  • Labeled_statement (etiketli deyimler) içinde belirtilen etiketin kapsamı, bildirimin gerçekleştiği bloğudur .The scope of a label declared in a labeled_statement (Labeled statements) is the block in which the declaration occurs.
  • Bir local_variable_declaration (yerel değişken bildirimleri) içinde belirtilen bir yerel değişkenin kapsamı, bildirimin gerçekleştiği bloğudur.The scope of a local variable declared in a local_variable_declaration (Local variable declarations) is the block in which the declaration occurs.
  • Bir deyimin switch_block bildirildiği bir yerel değişkenin kapsamı switch (switch ifadesinin) switch_block.The scope of a local variable declared in a switch_block of a switch statement (The switch statement) is the switch_block.
  • Bir deyimin for_initializer bildirildiği bir yerel değişkenin kapsamı for (for ifadesinin) for_initializer, for_condition, for_iterator ve deyimin içerilen deyimidir for .The scope of a local variable declared in a for_initializer of a for statement (The for statement) is the for_initializer, the for_condition, the for_iterator, and the contained statement of the for statement.
  • Bir local_constant_declaration (yerel sabit bildirimler) içinde belirtilen yerel bir sabit kapsam, bildirimin gerçekleştiği bloğudur.The scope of a local constant declared in a local_constant_declaration (Local constant declarations) is the block in which the declaration occurs. Bu, constant_declarator önündeki metinsel konumdaki yerel bir sabite başvuruda bulunmak için bir derleme zamanı hatasıdır.It is a compile-time error to refer to a local constant in a textual position that precedes its constant_declarator.
  • Foreach_statement, using_statement, lock_statement veya query_expression bir parçası olarak belirtilen bir değişkenin kapsamı, verilen yapının genişlemesiyle belirlenir.The scope of a variable declared as part of a foreach_statement, using_statement, lock_statement or query_expression is determined by the expansion of the given construct.

Bir ad alanı, sınıf, yapı veya numaralandırma üyesi kapsamında, üyeye üye bildiriminden önce gelen metinsel bir konumda başvurmak mümkündür.Within the scope of a namespace, class, struct, or enumeration member it is possible to refer to the member in a textual position that precedes the declaration of the member. Örneğin:For example

class A
{
    void F() {
        i = 1;
    }

    int i = 0;
}

Burada, F bildirilmeden önce başvurmak için geçerlidir i .Here, it is valid for F to refer to i before it is declared.

Yerel değişken kapsamında, yerel değişkenin local_variable_declarator önündeki bir metinsel konumdaki yerel değişkene başvurabileceğiniz bir derleme zamanı hatasıdır.Within the scope of a local variable, it is a compile-time error to refer to the local variable in a textual position that precedes the local_variable_declarator of the local variable. Örneğin:For example

class A
{
    int i = 0;

    void F() {
        i = 1;                  // Error, use precedes declaration
        int i;
        i = 2;
    }

    void G() {
        int j = (j = 1);        // Valid
    }

    void H() {
        int a = 1, b = ++a;    // Valid
    }
}

FYukarıdaki yöntemde, özellikle için ilk atama, i dış kapsamda belirtilen alana başvurmaz.In the F method above, the first assignment to i specifically does not refer to the field declared in the outer scope. Bunun yerine, yerel değişkene başvurur ve değişkenin bildiriminden önce metin içeriğini eklemek bir derleme zamanı hatasına neden olur.Rather, it refers to the local variable and it results in a compile-time error because it textually precedes the declaration of the variable. GYönteminde, j j kullanım local_variable_declarator önünde olmadığı için, bildirimi başlatıcısında öğesinin kullanımı geçerlidir.In the G method, the use of j in the initializer for the declaration of j is valid because the use does not precede the local_variable_declarator. HYönteminde, sonraki local_variable_declarator , aynı local_variable_declaration daha önceki bir local_variable_declarator belirtilen yerel bir değişkene doğru şekilde başvurur.In the H method, a subsequent local_variable_declarator correctly refers to a local variable declared in an earlier local_variable_declarator within the same local_variable_declaration.

Yerel değişkenlerin kapsam kuralları, bir ifade bağlamında kullanılan bir adın anlamını her zaman bir blok içinde aynı olduğundan emin olmak için tasarlanmıştır.The scoping rules for local variables are designed to guarantee that the meaning of a name used in an expression context is always the same within a block. Yerel bir değişkenin kapsamı yalnızca kendi bildiriminden bloğunun sonuna genişletirse, yukarıdaki örnekte, ilk atama örnek değişkenine atanır ve ikinci atama yerel değişkene atanır, bu da bloktaki deyimler daha sonra yeniden düzenlenmeye acaksa derleme zamanı hatalarına neden olur.If the scope of a local variable were to extend only from its declaration to the end of the block, then in the example above, the first assignment would assign to the instance variable and the second assignment would assign to the local variable, possibly leading to compile-time errors if the statements of the block were later to be rearranged.

Bir blok içindeki bir adın anlamı, adının kullanıldığı bağlama göre farklılık gösterebilir.The meaning of a name within a block may differ based on the context in which the name is used. ÖrnekteIn the example

using System;

class A {}

class Test
{
    static void Main() {
        string A = "hello, world";
        string s = A;                            // expression context

        Type t = typeof(A);                      // type context

        Console.WriteLine(s);                    // writes "hello, world"
        Console.WriteLine(t);                    // writes "A"
    }
}

ad, bir A ifade bağlamında, yerel değişkene A ve sınıfa başvurmak için bir tür bağlamına başvurmak için kullanılır A .the name A is used in an expression context to refer to the local variable A and in a type context to refer to the class A.

Ad gizlemeName hiding

Bir varlığın kapsamı genellikle varlığın bildirim alanından daha fazla program metnini kapsar.The scope of an entity typically encompasses more program text than the declaration space of the entity. Özellikle, bir varlığın kapsamı, aynı ada sahip varlıkları içeren yeni bildirim alanları sunan bildirimler içerebilir.In particular, the scope of an entity may include declarations that introduce new declaration spaces containing entities of the same name. Bu tür bildirimler özgün varlığın *gizli _ olmasına neden olur.Such declarations cause the original entity to become *hidden _. Buna karşılık, bir varlık gizlenmediği zaman _ görünür* olarak kabul edilir.Conversely, an entity is said to be _ visible* when it is not hidden.

Ad gizleme kapsamları, iç içe geçme yoluyla çakıştığında ve kapsamlar devralma yoluyla çakıştığında oluşur.Name hiding occurs when scopes overlap through nesting and when scopes overlap through inheritance. İki tür gizleme özelliği aşağıdaki bölümlerde açıklanmıştır.The characteristics of the two types of hiding are described in the following sections.

İç içe geçme yoluyla gizlemeHiding through nesting

İç içe geçme yoluyla ad alanları veya türler, sınıfların veya yapıların içinde iç içe geçme, parametre ve yerel değişken bildirimlerinin sonucu olarak, ad alanları içinde iç içe geçme işleminin sonucu olarak ortaya çıkabilir.Name hiding through nesting can occur as a result of nesting namespaces or types within namespaces, as a result of nesting types within classes or structs, and as a result of parameter and local variable declarations.

ÖrnekteIn the example

class A
{
    int i = 0;

    void F() {
        int i = 1;
    }

    void G() {
        i = 1;
    }
}

yöntemi içinde F , örnek değişkeni i yerel değişken tarafından gizlenir i , ancak G yönteminde, i hala örnek değişkenine başvurur.within the F method, the instance variable i is hidden by the local variable i, but within the G method, i still refers to the instance variable.

Bir iç kapsamdaki bir ad, dış kapsamdaki bir adı gizliyor, bu ada ait tüm aşırı yüklenmiş oluşumları gizler.When a name in an inner scope hides a name in an outer scope, it hides all overloaded occurrences of that name. ÖrnekteIn the example

class Outer
{
    static void F(int i) {}

    static void F(string s) {}

    class Inner
    {
        void G() {
            F(1);              // Invokes Outer.Inner.F
            F("Hello");        // Error
        }

        static void F(long l) {}
    }
}

çağrısı, F(1) F Inner öğesinin tüm dış oluşumları F iç bildirim tarafından gizlendiğinden, ' ın ' de belirtilen ' i çağırır.the call F(1) invokes the F declared in Inner because all outer occurrences of F are hidden by the inner declaration. Aynı nedenden dolayı çağrı, F("Hello") derleme zamanı hatası ile sonuçlanır.For the same reason, the call F("Hello") results in a compile-time error.

Devralma yoluyla gizlemeHiding through inheritance

Devralma yoluyla ad gizleme, sınıflar veya yapılar temel sınıflardan devralınan adları yeniden bildirdikleri zaman oluşur.Name hiding through inheritance occurs when classes or structs redeclare names that were inherited from base classes. Bu tür bir ad gizleme aşağıdaki biçimlerden birini alır:This type of name hiding takes one of the following forms:

  • Bir sınıf veya yapı içinde tanıtılan bir sabit, alan, özellik, olay veya tür, aynı ada sahip tüm temel sınıf üyelerini gizler.A constant, field, property, event, or type introduced in a class or struct hides all base class members with the same name.
  • Bir sınıf veya yapı içinde tanıtılan bir yöntem, aynı ada sahip tüm yöntem olmayan taban sınıf üyelerini ve aynı imzaya sahip tüm temel sınıf yöntemlerini (Yöntem adı ve parametre sayısı, değiştiriciler ve türler) gizler.A method introduced in a class or struct hides all non-method base class members with the same name, and all base class methods with the same signature (method name and parameter count, modifiers, and types).
  • Bir sınıf veya yapı içinde tanıtılan bir Dizin Oluşturucu, aynı imzaya sahip tüm temel sınıf dizin oluşturucularının (parametre sayısı ve türleri) tümünü gizler.An indexer introduced in a class or struct hides all base class indexers with the same signature (parameter count and types).

İşleç bildirimlerini (işleçler) yöneten kurallar, türetilmiş bir sınıfın bir taban sınıftaki işleçle aynı imzaya sahip bir işleç tanımlamasına olanak sağlar.The rules governing operator declarations (Operators) make it impossible for a derived class to declare an operator with the same signature as an operator in a base class. Bu nedenle, işleçler hiçbir şekilde bir tane gizlemez.Thus, operators never hide one another.

Bir dış kapsamdan bir adı gizlemenin aksine, devralınan bir kapsamdaki erişilebilir bir adı gizlemek bir uyarının raporlanmasına neden olur.Contrary to hiding a name from an outer scope, hiding an accessible name from an inherited scope causes a warning to be reported. ÖrnekteIn the example

class Base
{
    public void F() {}
}

class Derived: Base
{
    public void F() {}        // Warning, hiding an inherited name
}

içindeki bildirimi, F Derived bir uyarının bildirilmesine neden olur.the declaration of F in Derived causes a warning to be reported. Devralınan bir adın gizlenmesi, temel sınıfların ayrı bir evrimden daha fazla gelişmesinden dolayı özellikle bir hata değildir.Hiding an inherited name is specifically not an error, since that would preclude separate evolution of base classes. Örneğin, yukarıdaki durum, Base F sınıfının önceki bir sürümünde mevcut olmayan bir yöntem tanıtıldığı için hakkında daha fazla gelmiş olabilir.For example, the above situation might have come about because a later version of Base introduced an F method that wasn't present in an earlier version of the class. Yukarıdaki durum bir hata olduğundan, ayrı sürümlü Sınıf kitaplığındaki temel sınıfta yapılan herhangi bir değişiklik, türetilmiş sınıfların geçersiz olmasına neden olabilir.Had the above situation been an error, then any change made to a base class in a separately versioned class library could potentially cause derived classes to become invalid.

Devralınan bir adı gizlemeden kaynaklanan uyarı, değiştirici kullanılarak ortadan kaldırılabilir new :The warning caused by hiding an inherited name can be eliminated through use of the new modifier:

class Base
{
    public void F() {}
}

class Derived: Base
{
    new public void F() {}
}

newDeğiştirici, F içindeki ' in Derived "yeni" olduğunu ve bu, devralınan üyeyi gizlemek için gerçekten düşünülmediğini belirtir.The new modifier indicates that the F in Derived is "new", and that it is indeed intended to hide the inherited member.

Yeni bir üyenin bildirimi, devralınan bir üyeyi yalnızca yeni üyenin kapsamı içinde gizler.A declaration of a new member hides an inherited member only within the scope of the new member.

class Base
{
    public static void F() {}
}

class Derived: Base
{
    new private static void F() {}    // Hides Base.F in Derived only
}

class MoreDerived: Derived
{
    static void G() { F(); }          // Invokes Base.F
}

Yukarıdaki örnekte, ' ın bildirimi F Derived F öğesinden devralınmış olan öğesini gizler Base , ancak içindeki yeni ' nin F Derived özel erişimi olduğundan, kapsamı olarak genişletilmez MoreDerived .In the example above, the declaration of F in Derived hides the F that was inherited from Base, but since the new F in Derived has private access, its scope does not extend to MoreDerived. Bu nedenle, F() içindeki çağrısı MoreDerived.G geçerli olur ve çağırır Base.F .Thus, the call F() in MoreDerived.G is valid and will invoke Base.F.

Ad alanı ve tür adlarıNamespace and type names

C# programındaki birkaç bağlam, bir namespace_name veya type_name belirtilmesini gerektirir.Several contexts in a C# program require a namespace_name or a type_name to be specified.

namespace_name
    : namespace_or_type_name
    ;

type_name
    : namespace_or_type_name
    ;

namespace_or_type_name
    : identifier type_argument_list?
    | namespace_or_type_name '.' identifier type_argument_list?
    | qualified_alias_member
    ;

Namespace_name , bir ad alanına başvuran bir namespace_or_type_name .A namespace_name is a namespace_or_type_name that refers to a namespace. Aşağıda açıklandığı gibi çözüm aşağıdaki şekilde, bir namespace_name namespace_or_type_name bir ad alanına başvurmalıdır veya bir derleme zamanı hatası oluşur.Following resolution as described below, the namespace_or_type_name of a namespace_name must refer to a namespace, or otherwise a compile-time error occurs. Hiçbir tür bağımsız değişkeni (tür bağımsızdeğişkeni) bir namespace_name bulunabilir (yalnızca türler tür bağımsız değişkenlerine sahip olabilir).No type arguments (Type arguments) can be present in a namespace_name (only types can have type arguments).

Type_name , bir türe başvuran bir namespace_or_type_name .A type_name is a namespace_or_type_name that refers to a type. Aşağıda açıklandığı gibi, aşağıda açıklandığı gibi, bir type_name namespace_or_type_name bir türe başvurmalıdır veya bir derleme zamanı hatası oluşur.Following resolution as described below, the namespace_or_type_name of a type_name must refer to a type, or otherwise a compile-time error occurs.

Namespace_or_type_name nitelikli bir diğer ad üyesiyse, anlamı ad alanı diğer ad niteleyicileribölümünde açıklanacaktır.If the namespace_or_type_name is a qualified-alias-member its meaning is as described in Namespace alias qualifiers. Aksi takdirde, namespace_or_type_name dört formdan birine sahiptir:Otherwise, a namespace_or_type_name has one of four forms:

  • I
  • I<A1, ..., Ak>
  • N.I
  • N.I<A1, ..., Ak>

Itek bir tanımlayıcıdır, N bir namespace_or_type_name ve <A1, ..., Ak> isteğe bağlı bir type_argument_list.where I is a single identifier, N is a namespace_or_type_name and <A1, ..., Ak> is an optional type_argument_list. Type_argument_list belirtilmediğinde sıfır olduğunu düşünün k .When no type_argument_list is specified, consider k to be zero.

Bir namespace_or_type_name anlamı aşağıdaki şekilde belirlenir:The meaning of a namespace_or_type_name is determined as follows:

  • Namespace_or_type_name , veya formundadır I I<A1, ..., Ak> :If the namespace_or_type_name is of the form I or of the form I<A1, ..., Ak>:
    • KSıfırsa ve namespace_or_type_name bir genel yöntem bildirimi (metotlar) içinde görünürse ve bu bildirimde ada sahip bir tür parametresi (tür parametreleri) varsa  I namespace_or_type_name bu tür parametresine başvurur.If K is zero and the namespace_or_type_name appears within a generic method declaration (Methods) and if that declaration includes a type parameter (Type parameters) with name I, then the namespace_or_type_name refers to that type parameter.
    • Aksi takdirde, namespace_or_type_name bir tür bildiriminde görünürse her örnek türü  T (örnek türü) için, bu tür bildiriminin örnek türüyle başlayıp her bir kapsayan sınıfın ya da yapı bildiriminin örnek türüyle (varsa) devam eder:Otherwise, if the namespace_or_type_name appears within a type declaration, then for each instance type T (The instance type), starting with the instance type of that type declaration and continuing with the instance type of each enclosing class or struct declaration (if any):
      • KSıfırsa ve bildirimi, T adında bir tür parametresi içeriyorsa  I , namespace_or_type_name bu tür parametreye başvurur.If K is zero and the declaration of T includes a type parameter with name I, then the namespace_or_type_name refers to that type parameter.
      • Aksi takdirde, namespace_or_type_name tür bildiriminin gövdesinde görüntüleniyorsa ve T ya da temel türlerinden biri ad ve tür parametrelerine sahip bir iç içe erişilebilir tür içeriyorsa  I K   , namespace_or_type_name verilen tür bağımsız değişkenleriyle oluşturulan bu türe başvurur.Otherwise, if the namespace_or_type_name appears within the body of the type declaration, and T or any of its base types contain a nested accessible type having name I and K type parameters, then the namespace_or_type_name refers to that type constructed with the given type arguments. Böyle birden fazla tür varsa, daha fazla türetilmiş tür içinde belirtilen tür seçilidir.If there is more than one such type, the type declared within the more derived type is selected. Tür olmayan üyelerin (sabitler, alanlar, Yöntemler, özellikler, Dizin oluşturucular, işleçler, örnek oluşturucular, Yıkıcılar ve statik oluşturucular) ve namespace_or_type_name anlamı belirlenirken farklı sayıda tür parametresi olan tür üyelerinin yok sayılacağını unutmayın.Note that non-type members (constants, fields, methods, properties, indexers, operators, instance constructors, destructors, and static constructors) and type members with a different number of type parameters are ignored when determining the meaning of the namespace_or_type_name.
    • Önceki adımlar başarısız olduysa, her ad alanı için  N namespace_or_type_name gerçekleştiği ad alanından başlayarak, kapsayan her ad alanıyla (varsa) devam eder ve genel ad alanıyla sona eriyor, aşağıdaki adımlar bir varlık bulunana kadar değerlendirilir:If the previous steps were unsuccessful then, for each namespace N, starting with the namespace in which the namespace_or_type_name occurs, continuing with each enclosing namespace (if any), and ending with the global namespace, the following steps are evaluated until an entity is located:
      • KSıfırsa ve I içindeki bir ad alanının adı ise  N :If K is zero and I is the name of a namespace in N, then:
        • Namespace_or_type_name gerçekleştiği konum için bir ad alanı bildirimi alıyorsa N ve ad alanı bildirimi adı bir ad alanı veya türle ilişkilendiren bir extern_alias_directive veya using_alias_directive içeriyorsa  I , namespace_or_type_name belirsizdir ve derleme zamanı hatası oluşur.If the location where the namespace_or_type_name occurs is enclosed by a namespace declaration for N and the namespace declaration contains an extern_alias_directive or using_alias_directive that associates the name I with a namespace or type, then the namespace_or_type_name is ambiguous and a compile-time error occurs.
        • Aksi takdirde namespace_or_type_name , içinde adlı ad alanını ifade I eder N .Otherwise, the namespace_or_type_name refers to the namespace named I in N.
      • Aksi takdirde, N ad  I ve K tür parametrelerine sahip erişilebilir bir tür içeriyorsa   :Otherwise, if N contains an accessible type having name I and K type parameters, then:
        • KSıfırsa ve namespace_or_type_name gerçekleştiği konum için bir ad alanı bildirimi alınır N ve ad alanı bildirimi adı bir ad alanı veya türle ilişkilendiren bir extern_alias_directive veya using_alias_directive içeriyorsa  I , namespace_or_type_name belirsizdir ve bir derleme zamanı hatası oluşur.If K is zero and the location where the namespace_or_type_name occurs is enclosed by a namespace declaration for N and the namespace declaration contains an extern_alias_directive or using_alias_directive that associates the name I with a namespace or type, then the namespace_or_type_name is ambiguous and a compile-time error occurs.
        • Aksi takdirde namespace_or_type_name , verilen tür bağımsız değişkenleriyle oluşturulan türe başvurur.Otherwise, the namespace_or_type_name refers to the type constructed with the given type arguments.
      • Aksi takdirde, namespace_or_type_name gerçekleştiği konum için bir ad alanı bildirimi alınır N :Otherwise, if the location where the namespace_or_type_name occurs is enclosed by a namespace declaration for N:
        • KSıfırsa ve ad alanı bildirimi, adı bir içeri aktarılan ad alanı veya türle ilişkilendiren bir extern_alias_directive veya using_alias_directive içeriyorsa  I namespace_or_type_name bu ad alanına veya türe başvurur.If K is zero and the namespace declaration contains an extern_alias_directive or using_alias_directive that associates the name I with an imported namespace or type, then the namespace_or_type_name refers to that namespace or type.
        • Aksi takdirde, using_namespace_directive s ve ad alanı bildiriminin using_alias_directive tarafından içeri aktarılan ad alanları ve tür bildirimleri, ad ve tür parametrelerine sahip tam olarak bir erişilebilir tür içeriyorsa  I K   , namespace_or_type_name verilen tür bağımsız değişkenleriyle oluşturulan bu türe başvurur.Otherwise, if the namespaces and type declarations imported by the using_namespace_directive s and using_alias_directive s of the namespace declaration contain exactly one accessible type having name I and K type parameters, then the namespace_or_type_name refers to that type constructed with the given type arguments.
        • Aksi takdirde, using_namespace_directive s ve ad alanı bildiriminin using_alias_directive tarafından içeri aktarılan ad alanları ve tür bildirimleri, ad ve tür parametrelerine sahip birden fazla erişilebilir tür  I içeriyorsa K   , namespace_or_type_name belirsizdir ve bir hata oluşur.Otherwise, if the namespaces and type declarations imported by the using_namespace_directive s and using_alias_directive s of the namespace declaration contain more than one accessible type having name I and K type parameters, then the namespace_or_type_name is ambiguous and an error occurs.
    • Aksi takdirde, namespace_or_type_name tanımsız olur ve derleme zamanı hatası oluşur.Otherwise, the namespace_or_type_name is undefined and a compile-time error occurs.
  • Aksi takdirde namespace_or_type_name , N.I veya formundadır N.I<A1, ..., Ak> .Otherwise, the namespace_or_type_name is of the form N.I or of the form N.I<A1, ..., Ak>. N İlk olarak bir namespace_or_type_name olarak çözümlenir.N is first resolved as a namespace_or_type_name. Çözümlemesi N başarılı olmazsa, bir derleme zamanı hatası oluşur.If the resolution of N is not successful, a compile-time error occurs. Aksi takdirde N.I veya N.I<A1, ..., Ak> aşağıdaki şekilde çözümlenir:Otherwise, N.I or N.I<A1, ..., Ak> is resolved as follows:
    • KSıfır ise ve N bir ad alanına başvuruyorsa ve N ada sahip bir iç içe ad alanı içeriyorsa I namespace_or_type_name , bu iç içe geçmiş ad alanına başvurur.If K is zero and N refers to a namespace and N contains a nested namespace with name I, then the namespace_or_type_name refers to that nested namespace.
    • Aksi takdirde, N bir ad alanına başvurur ve N ad ve tür parametrelerine sahip erişilebilir bir tür içeriyorsa  I K   namespace_or_type_name , belirtilen tür bağımsız değişkenleriyle oluşturulan bu türe başvurur.Otherwise, if N refers to a namespace and N contains an accessible type having name I and K type parameters, then the namespace_or_type_name refers to that type constructed with the given type arguments.
    • Aksi takdirde, N (Belki de oluşturulmuş) bir sınıfa veya yapı türüne N veya temel sınıflarından birine başvuruyorsa, ad ve tür parametrelerine sahip iç içe erişilebilir bir tür içeriyorsa  I K   namespace_or_type_name , verilen tür bağımsız değişkenleriyle oluşturulan bu türe başvurur.Otherwise, if N refers to a (possibly constructed) class or struct type and N or any of its base classes contain a nested accessible type having name I and K type parameters, then the namespace_or_type_name refers to that type constructed with the given type arguments. Böyle birden fazla tür varsa, daha fazla türetilmiş tür içinde belirtilen tür seçilidir.If there is more than one such type, the type declared within the more derived type is selected. Öğesinin anlamı N.I temel sınıf belirtiminin çözümlenme parçası olarak belirleniyorsa, N doğrudan taban sınıfının N nesne (temel sınıflar) olarak kabul edilir.Note that if the meaning of N.I is being determined as part of resolving the base class specification of N then the direct base class of N is considered to be object (Base classes).
    • Aksi takdirde, N.I geçersiz bir namespace_or_type_name ve derleme zamanı hatası oluşur.Otherwise, N.I is an invalid namespace_or_type_name, and a compile-time error occurs.

Namespace_or_type_name bir statik sınıfa (statik sınıflar) başvurmak için yalnızcaA namespace_or_type_name is permitted to reference a static class (Static classes) only if

  • Namespace_or_type_name , T formun namespace_or_type_name T.I veyaThe namespace_or_type_name is the T in a namespace_or_type_name of the form T.I, or
  • Namespace_or_type_name , T formun bir typeof_expression (bağımsız değişken listeleri1) typeof(T) .The namespace_or_type_name is the T in a typeof_expression (Argument lists1) of the form typeof(T).

Tam nitelikli adlarFully qualified names

Her ad alanı ve türün, tüm diğerleri arasından ad alanını veya türü benzersiz bir şekilde tanımlayan tam bir adı vardır.Every namespace and type has a fully qualified name, which uniquely identifies the namespace or type amongst all others. Bir ad alanının veya türün tam nitelikli adı N Şu şekilde belirlenir:The fully qualified name of a namespace or type N is determined as follows:

  • NGenel ad alanının üyesiyse, tam adı ' dir N .If N is a member of the global namespace, its fully qualified name is N.
  • Aksi takdirde, tam adı ' dir; S.N burada, S içinde bildirildiği ad alanının veya türün tam nitelikli adıdır N .Otherwise, its fully qualified name is S.N, where S is the fully qualified name of the namespace or type in which N is declared.

Diğer bir deyişle, tam nitelikli adı N N , genel ad alanından başlayarak, ' ın sunduğu tanımlayıcıların tam hiyerarşik yoludur.In other words, the fully qualified name of N is the complete hierarchical path of identifiers that lead to N, starting from the global namespace. Bir ad alanının veya türün her üyesinin benzersiz bir adı olması gerektiğinden, bir ad alanının veya türün tam nitelikli adının her zaman benzersiz olması gerekir.Because every member of a namespace or type must have a unique name, it follows that the fully qualified name of a namespace or type is always unique.

Aşağıdaki örnekte, ilişkili tam adlarıyla birlikte çeşitli ad alanı ve tür bildirimleri gösterilmektedir.The example below shows several namespace and type declarations along with their associated fully qualified names.

class A {}                // A

namespace X               // X
{
    class B               // X.B
    {
        class C {}        // X.B.C
    }

    namespace Y           // X.Y
    {
        class D {}        // X.Y.D
    }
}

namespace X.Y             // X.Y
{
    class E {}            // X.Y.E
}

Otomatik bellek yönetimiAutomatic memory management

C#, geliştiricilerin nesnelerin kapladığı belleği el ile ayırmayı ve boşaltmasını sağlayan otomatik bellek yönetimini kullanır.C# employs automatic memory management, which frees developers from manually allocating and freeing the memory occupied by objects. Otomatik bellek yönetimi ilkeleri bir çöp toplayıcısı tarafından uygulanır.Automatic memory management policies are implemented by a garbage collector. Bir nesnenin bellek yönetimi yaşam döngüsü aşağıdaki gibidir:The memory management life cycle of an object is as follows:

  1. Nesne oluşturulduğunda, için bellek ayrılır, Oluşturucu çalıştırılır ve nesne canlı olarak değerlendirilir.When the object is created, memory is allocated for it, the constructor is run, and the object is considered live.
  2. Nesneye veya herhangi bir kısmına, yok edicilerin çalışması dışında, yürütmenin olası devamlılığı tarafından erişilemez, nesne artık kullanımda değildir ve yok etme için uygun hale gelir.If the object, or any part of it, cannot be accessed by any possible continuation of execution, other than the running of destructors, the object is considered no longer in use, and it becomes eligible for destruction. C# derleyicisi ve çöp toplayıcı, bir nesneye yapılan başvuruların gelecekte kullanılabileceğini belirlemek için kodu analiz etmeyi tercih edebilir.The C# compiler and the garbage collector may choose to analyze code to determine which references to an object may be used in the future. Örneğin, kapsamdaki bir yerel değişken bir nesneye yönelik tek başvuru ise, ancak bu yerel değişken yordamda geçerli yürütme noktasından yürütmenin olası hiçbir devamlılığı hiçbir şekilde başvurulmuyorsa, çöp toplayıcı, nesneyi artık kullanımda olmayacak şekilde ele alabilir (ancak gerekli değildir).For instance, if a local variable that is in scope is the only existing reference to an object, but that local variable is never referred to in any possible continuation of execution from the current execution point in the procedure, the garbage collector may (but is not required to) treat the object as no longer in use.
  3. Nesne yok etme için uygun olduğunda, bazı belirtilmemişse nesne için yıkıcı (yokediciler) (varsa) çalıştırılır.Once the object is eligible for destruction, at some unspecified later time the destructor (Destructors) (if any) for the object is run. Normal koşullarda nesnenin yıkıcısı yalnızca bir kez çalıştırılır, ancak uygulamaya özgü API 'Ler bu davranışın geçersiz kılınmasına izin verebilir.Under normal circumstances the destructor for the object is run once only, though implementation-specific APIs may allow this behavior to be overridden.
  4. Bir nesnenin yıkıcısı çalıştırıldığında, bu nesneye veya bunun herhangi bir kısmına, yok edicinin çalıştırılması dahil olmak üzere herhangi bir olası yürütme devamlılığı tarafından erişilemez, nesnenin erişilemez olduğu kabul edilir ve nesne koleksiyona uygun hale gelir.Once the destructor for an object is run, if that object, or any part of it, cannot be accessed by any possible continuation of execution, including the running of destructors, the object is considered inaccessible and the object becomes eligible for collection.
  5. Son olarak, nesne koleksiyon için uygun olduktan sonra çöp toplayıcı bu nesneyle ilişkili belleği serbest bırakır.Finally, at some time after the object becomes eligible for collection, the garbage collector frees the memory associated with that object.

Çöp toplayıcı, nesne kullanımı hakkındaki bilgileri tutar ve bu bilgileri kullanarak yeni oluşturulan bir nesneyi bulma, bir nesnenin konumunu değiştirme ve bir nesnenin artık ne zaman ne zaman kullanıldığı veya erişilemeyen gibi bellek yönetimi kararları almak için kullanılır.The garbage collector maintains information about object usage, and uses this information to make memory management decisions, such as where in memory to locate a newly created object, when to relocate an object, and when an object is no longer in use or inaccessible.

Çöp toplayıcısının varlığını varsaymış diğer diller gibi, C# ise çöp toplayıcının çok çeşitli bellek yönetimi ilkeleri uygulayabilmesi için tasarlanmıştır.Like other languages that assume the existence of a garbage collector, C# is designed so that the garbage collector may implement a wide range of memory management policies. Örnek olarak, C#, yok edicilerin çalıştırılmasını veya uygun olan herhangi bir sırada ya da belirli bir iş parçacığında çalışan yok edicilerin çalıştırılmasını gerektirmez.For instance, C# does not require that destructors be run or that objects be collected as soon as they are eligible, or that destructors be run in any particular order, or on any particular thread.

Çöp toplayıcısının davranışı, sınıftaki statik yöntemler aracılığıyla bir ölçüde denetlenebilir System.GC .The behavior of the garbage collector can be controlled, to some degree, via static methods on the class System.GC. Bu sınıf, bir koleksiyon oluşmasına, çalıştırılacak yok edicilere (veya çalıştırılmayan), vb. istemek için kullanılabilir.This class can be used to request a collection to occur, destructors to be run (or not run), and so forth.

Çöp toplayıcısının nesnelerin ne zaman toplanmaya karar verirken ve yıkıcıları çalıştırmanın yanı sıra, uygun bir uygulama aşağıdaki kodla gösterilenden farklı bir çıktı üretebilir.Since the garbage collector is allowed wide latitude in deciding when to collect objects and run destructors, a conforming implementation may produce output that differs from that shown by the following code. ProgramThe program

using System;

class A
{
    ~A() {
        Console.WriteLine("Destruct instance of A");
    }
}

class B
{
    object Ref;

    public B(object o) {
        Ref = o;
    }

    ~B() {
        Console.WriteLine("Destruct instance of B");
    }
}

class Test
{
    static void Main() {
        B b = new B(new A());
        b = null;
        GC.Collect();
        GC.WaitForPendingFinalizers();
    }
}

sınıfının bir örneğini ve sınıfının bir örneğini oluşturur A B .creates an instance of class A and an instance of class B. Bu nesneler, değişkene b değer atandığında null , bu süre dolduktan sonra Kullanıcı tarafından yazılan herhangi bir kodun bunlara erişebilmesi olanaksız olduğundan çöp toplama için uygun hale gelir.These objects become eligible for garbage collection when the variable b is assigned the value null, since after this time it is impossible for any user-written code to access them. Çıktı şunlardan biri olabilirThe output could be either

Destruct instance of A
Destruct instance of B

veyaor

Destruct instance of B
Destruct instance of A

dil, nesnelerin atık olarak toplandığı sıraya göre hiçbir kısıtlama yapmadığından.because the language imposes no constraints on the order in which objects are garbage collected.

Hafif durumlarda, "yok etme için uygun" ve "koleksiyon için uygun" arasındaki ayrım önemli olabilir.In subtle cases, the distinction between "eligible for destruction" and "eligible for collection" can be important. Örneğin,For example,

using System;

class A
{
    ~A() {
        Console.WriteLine("Destruct instance of A");
    }

    public void F() {
        Console.WriteLine("A.F");
        Test.RefA = this;
    }
}

class B
{
    public A Ref;

    ~B() {
        Console.WriteLine("Destruct instance of B");
        Ref.F();
    }
}

class Test
{
    public static A RefA;
    public static B RefB;

    static void Main() {
        RefB = new B();
        RefA = new A();
        RefB.Ref = RefA;
        RefB = null;
        RefA = null;

        // A and B now eligible for destruction
        GC.Collect();
        GC.WaitForPendingFinalizers();

        // B now eligible for collection, but A is not
        if (RefA != null)
            Console.WriteLine("RefA is not null");
    }
}

Yukarıdaki programda, atık toplayıcı, yok edicinin önüne yok ediciyi çalıştırmayı seçerse A B , bu programın çıktısı şu olabilir:In the above program, if the garbage collector chooses to run the destructor of A before the destructor of B, then the output of this program might be:

Destruct instance of A
Destruct instance of B
A.F
RefA is not null

Öğesinin örneği A kullanımda değil ve A yok edicisi çalıştırılsa da, A F başka bir yıkıcıdan (Bu durumda) yöntemlerin çağrılması hala mümkündür.Note that although the instance of A was not in use and A's destructor was run, it is still possible for methods of A (in this case, F) to be called from another destructor. Ayrıca, bir yıkıcı çalıştırmanın bir nesnenin ana hat programından yeniden kullanılabilir hale gelmesine neden olabileceğini unutmayın.Also, note that running of a destructor may cause an object to become usable from the mainline program again. Bu durumda, öğesinin B yıkıcısı, A daha önce canlı başvurudan erişilebilir hale gelmesi için kullanımda olmayan bir örneğine neden oldu Test.RefA .In this case, the running of B's destructor caused an instance of A that was previously not in use to become accessible from the live reference Test.RefA. ' A çağrısından sonra WaitForPendingFinalizers , örneği B koleksiyon için uygundur, ancak öğesinin örneği A başvuru nedeniyle değildir Test.RefA .After the call to WaitForPendingFinalizers, the instance of B is eligible for collection, but the instance of A is not, because of the reference Test.RefA.

Karışıklıkları ve beklenmedik davranışları önlemek için, yok edicilerin yalnızca kendi nesnelerinde depolanan verilerde temizlik yapması ve başvurulan nesneler veya statik alanlar üzerinde herhangi bir eylem gerçekleştirmemek için iyi bir fikir vardır.To avoid confusion and unexpected behavior, it is generally a good idea for destructors to only perform cleanup on data stored in their object's own fields, and not to perform any actions on referenced objects or static fields.

Yıkıcıları kullanmanın bir alternatifi, bir sınıfın arabirimini uygulamasına olanak tanır System.IDisposable .An alternative to using destructors is to let a class implement the System.IDisposable interface. Bu, nesne istemcisinin, genellikle nesnesine bir bildirimde kaynak olarak erişerek using (using ifadesiyle) nesne kaynaklarını nasıl yayınleyeceğini belirlemesine izin verir.This allows the client of the object to determine when to release the resources of the object, typically by accessing the object as a resource in a using statement (The using statement).

Yürütme sırasıExecution order

Bir C# programının yürütülmesi, yürütülen her iş parçacığının yan etkileri kritik yürütme noktalarında korunacağından devam eder.Execution of a C# program proceeds such that the side effects of each executing thread are preserved at critical execution points. Bir yan etkisi , geçici bir alan okuma veya yazma, geçici olmayan bir değişkene yazma, bir dış kaynağa yazma ve özel durum atma olarak tanımlanır.A side effect is defined as a read or write of a volatile field, a write to a non-volatile variable, a write to an external resource, and the throwing of an exception. Bu yan etkileri sırasının korunması gereken kritik yürütme noktaları, geçici alanlar (geçici alanlar), lock deyimler (kilit deyimi) ve iş parçacığı oluşturma ve sonlandırma için referanslardır.The critical execution points at which the order of these side effects must be preserved are references to volatile fields (Volatile fields), lock statements (The lock statement), and thread creation and termination. Yürütme ortamı, bir C# programının yürütme sırasını değiştirmek için ücretsizdir ve aşağıdaki kısıtlamalara tabidir:The execution environment is free to change the order of execution of a C# program, subject to the following constraints:

  • Veri bağımlılığı, yürütme iş parçacığı içinde korunur.Data dependence is preserved within a thread of execution. Diğer bir deyişle, her değişkenin değeri iş parçacığındaki tüm deyimler orijinal program sırasıyla yürütülürse olarak hesaplanır.That is, the value of each variable is computed as if all statements in the thread were executed in original program order.
  • Başlatma sırası kuralları korunur (alan başlatma ve değişken başlatıcıları).Initialization ordering rules are preserved (Field initialization and Variable initializers).
  • Yan etkileri sıralaması, geçici okuma ve yazma işlemleri (geçici alanlar) açısından korunur.The ordering of side effects is preserved with respect to volatile reads and writes (Volatile fields). Ayrıca, bu ifadenin değerinin kullanılmadığını ve gerekli yan etkileri üretilmez (bir yöntemi çağırarak veya geçici bir alana erişim nedeniyle oluşan herhangi biri dahil), yürütme ortamı bir ifadenin bir kısmını değerlendirmemelidir.Additionally, the execution environment need not evaluate part of an expression if it can deduce that that expression's value is not used and that no needed side effects are produced (including any caused by calling a method or accessing a volatile field). Program yürütme zaman uyumsuz bir olay (örneğin, başka bir iş parçacığı tarafından oluşturulan bir özel durum) tarafından kesintiye uğradığında, observable yan etkilerinin orijinal program sırasıyla görünür olması garanti edilmez.When program execution is interrupted by an asynchronous event (such as an exception thrown by another thread), it is not guaranteed that the observable side effects are visible in the original program order.