DeyimlerStatements
C# çeşitli deyimler sağlar.C# provides a variety of statements. Bu deyimlerin çoğu C ve C++ içinde programlanan geliştiricilere tanıdık gelecektir.Most of these statements will be familiar to developers who have programmed in C and C++.
statement
: labeled_statement
| declaration_statement
| embedded_statement
;
embedded_statement
: block
| empty_statement
| expression_statement
| selection_statement
| iteration_statement
| jump_statement
| try_statement
| checked_statement
| unchecked_statement
| lock_statement
| using_statement
| yield_statement
| embedded_statement_unsafe
;
Embedded_statement olmayan Terminal, diğer deyimler içinde görünen deyimler için kullanılır.The embedded_statement nonterminal is used for statements that appear within other statements. Deyimi yerine embedded_statement kullanımı, bu bağlamlarda bildirim deyimlerinin ve etiketli deyimlerin kullanımını dışlar.The use of embedded_statement rather than statement excludes the use of declaration statements and labeled statements in these contexts. ÖrnekteThe example
void F(bool b) {
if (b)
int i = 44;
}
bir if
deyimin If dalı için bir ifade yerine embedded_statement gerektirdiğinden derleme zamanı hatası oluşur.results in a compile-time error because an if
statement requires an embedded_statement rather than a statement for its if branch. Bu koda izin verildiğinde, değişken i
bildirilebilecek, ancak hiçbir şekilde kullanılamaz.If this code were permitted, then the variable i
would be declared, but it could never be used. Ancak, i
bir blokta bildirimi yerleştirilerek örneğin geçerli olduğunu unutmayın.Note, however, that by placing i
's declaration in a block, the example is valid.
Bitiş noktaları ve ulaşılabilirlikEnd points and reachability
Her deyimin bir uç noktası vardır.Every statement has an end point. Sezgisel koşullarda, bir deyimin bitiş noktası, deyimden hemen sonraki konumdur.In intuitive terms, the end point of a statement is the location that immediately follows the statement. Bileşik deyimler için yürütme kuralları (katıştırılmış deyimler içeren deyimler), denetimin gömülü bir deyimin bitiş noktasına ulaştığında gerçekleştirilecek eylemi belirtir.The execution rules for composite statements (statements that contain embedded statements) specify the action that is taken when control reaches the end point of an embedded statement. Örneğin, denetim bir blok içindeki bir deyimin bitiş noktasına ulaştığında denetim bloğunda bir sonraki ifadeye aktarılır.For example, when control reaches the end point of a statement in a block, control is transferred to the next statement in the block.
Bir ifadeye, yürütme tarafından büyük olasılıkla ulaşılırsa, ifadeye *ulaşılabilir _ olarak söylenebilir.If a statement can possibly be reached by execution, the statement is said to be *reachable _. Buna karşılık, bir deyimin yürütülemeyecek bir olasılık yoksa, deyimin _ ulaşılamaz * olduğu söylenir.Conversely, if there is no possibility that a statement will be executed, the statement is said to be _*unreachable**.
ÖrnekteIn the example
void F() {
Console.WriteLine("reachable");
goto Label;
Console.WriteLine("unreachable");
Label:
Console.WriteLine("reachable");
}
Console.WriteLine
ifadesinin yürütülebilmesi olası bir olasılık olmadığından, öğesinin ikinci çağrısı ulaşılamaz.the second invocation of Console.WriteLine
is unreachable because there is no possibility that the statement will be executed.
Derleyici bir deyimin ulaşılamaz olduğunu belirlerse bir uyarı bildirilir.A warning is reported if the compiler determines that a statement is unreachable. Bir deyimin ulaşılamaz olması için özellikle bir hata değildir.It is specifically not an error for a statement to be unreachable.
Belirli bir deyimin veya bitiş noktasının erişilebilir olup olmadığını anlamak için, derleyici her bir bildirimde tanımlanan erişilebilir kurallara göre Akış Analizi gerçekleştirir.To determine whether a particular statement or end point is reachable, the compiler performs flow analysis according to the reachability rules defined for each statement. Akış Analizi, deyimlerin davranışını denetleyen sabit ifadelerin (sabit ifadeler) değerlerini hesaba alır, ancak sabit olmayan ifadelerin olası değerleri dikkate alınmaz.The flow analysis takes into account the values of constant expressions (Constant expressions) that control the behavior of statements, but the possible values of non-constant expressions are not considered. Diğer bir deyişle, denetim akışı analizinin amaçları doğrultusunda, belirli bir türün sabit olmayan bir ifadesi söz konusu türde herhangi bir olası değere sahip olduğu kabul edilir.In other words, for purposes of control flow analysis, a non-constant expression of a given type is considered to have any possible value of that type.
ÖrnekteIn the example
void F() {
const int i = 1;
if (i == 2) Console.WriteLine("unreachable");
}
işlecin Boolean ifadesi if
sabit bir ifadedir çünkü her iki işleç işlenenleri de ==
sabitler.the boolean expression of the if
statement is a constant expression because both operands of the ==
operator are constants. Sabit ifade derleme zamanında değerlendirildiğinden, değeri üreten false
Console.WriteLine
çağrının ulaşılamaz olduğu kabul edilir.As the constant expression is evaluated at compile-time, producing the value false
, the Console.WriteLine
invocation is considered unreachable. Ancak, i
yerel bir değişken olarak değiştirilirseHowever, if i
is changed to be a local variable
void F() {
int i = 1;
if (i == 2) Console.WriteLine("reachable");
}
Console.WriteLine
çağrının erişilebilir olduğu kabul edilir, ancak gerçekte hiçbir şekilde yürütülmeyecektir.the Console.WriteLine
invocation is considered reachable, even though, in reality, it will never be executed.
Bir işlev üyesinin bloğu her zaman ulaşılabilir olarak değerlendirilir.The block of a function member is always considered reachable. Bir blok içindeki her bir deyimin erişilebilirlik kurallarını kapsamlı bir şekilde değerlendirerek, belirli bir deyimin erişilebilirliği belirlenebilir.By successively evaluating the reachability rules of each statement in a block, the reachability of any given statement can be determined.
ÖrnekteIn the example
void F(int x) {
Console.WriteLine("start");
if (x < 0) Console.WriteLine("negative");
}
İkincinin ulaşılabilirlik Console.WriteLine
aşağıdaki gibi belirlenir:the reachability of the second Console.WriteLine
is determined as follows:
Console.WriteLine
Metodun bloğu erişilebilir olduğundan ilk ifade deyimine erişilebilirF
.The firstConsole.WriteLine
expression statement is reachable because the block of theF
method is reachable.- İlk
Console.WriteLine
ifade deyiminin bitiş noktasına ulaşılabilir çünkü bu deyim erişilebilir durumda.The end point of the firstConsole.WriteLine
expression statement is reachable because that statement is reachable. if
İlk ifade deyiminin bitiş noktası erişilebilir olduğundan deyim erişilebilirConsole.WriteLine
.Theif
statement is reachable because the end point of the firstConsole.WriteLine
expression statement is reachable.Console.WriteLine
Deyimin Boole ifadesiif
sabit değere sahip olmadığından ikinci ifade deyimine erişilebilirfalse
.The secondConsole.WriteLine
expression statement is reachable because the boolean expression of theif
statement does not have the constant valuefalse
.
Bir deyimin bitiş noktasında erişilebilir olması için derleme zamanı hatası olduğu iki durum vardır:There are two situations in which it is a compile-time error for the end point of a statement to be reachable:
- İfade,
switch
bir switch bölümünün bir sonraki Switch bölümüne "Fall" olarak geçmesine izin vermediğinden, bir switch bölümünün bildirim listesinin bitiş noktası için bir derleme zamanı hatası, erişilebilir olacaktır.Because theswitch
statement does not permit a switch section to "fall through" to the next switch section, it is a compile-time error for the end point of the statement list of a switch section to be reachable. Bu hata oluşursa, genellikle bir deyimin eksik olduğunun bir göstergesidirbreak
.If this error occurs, it is typically an indication that abreak
statement is missing. - Bu, erişilebilen bir değeri hesaplayan bir işlev üyesinin bloğunun bitiş noktası için derleme zamanı hatasıdır.It is a compile-time error for the end point of the block of a function member that computes a value to be reachable. Bu hata oluşursa, genellikle bir
return
deyimin eksik olduğunun göstergesidir.If this error occurs, it typically is an indication that areturn
statement is missing.
BloklarBlocks
Bir blok , tek bir ifadeye izin verilen bağlamlarda birden çok deyimin yazılmasına izin verir.A block permits multiple statements to be written in contexts where a single statement is allowed.
block
: '{' statement_list? '}'
;
Bir blok , küme ayraçları içine alınmış bir isteğe bağlı statement_list (ifade listeleri) oluşur.A block consists of an optional statement_list (Statement lists), enclosed in braces. Ekstre listesi atlanırsa, blok boş olarak kabul edilir.If the statement list is omitted, the block is said to be empty.
Bir blok, bildirim deyimleri içerebilir (bildirim deyimleri).A block may contain declaration statements (Declaration statements). Bir blok içinde belirtilen yerel bir değişken veya sabit kapsam, bloğudur.The scope of a local variable or constant declared in a block is the block.
Bir blok aşağıdaki gibi yürütülür:A block is executed as follows:
- Blok boşsa denetim, bloğun bitiş noktasına aktarılır.If the block is empty, control is transferred to the end point of the block.
- Blok boş değilse denetim, ifade listesine aktarılır.If the block is not empty, control is transferred to the statement list. Ve denetimi, ekstre listesinin bitiş noktasına ulaştığında denetim, bloğun bitiş noktasına aktarılır.When and if control reaches the end point of the statement list, control is transferred to the end point of the block.
Bloğun kendisi erişilebilir olduğunda bir bloğun ifade listesi erişilebilir olur.The statement list of a block is reachable if the block itself is reachable.
Blok boşsa veya ekstre listesinin bitiş noktası ulaşılabilir ise bir bloğun bitiş noktası erişilebilir olur.The end point of a block is reachable if the block is empty or if the end point of the statement list is reachable.
Bir veya daha fazla yield
deyim (Yield deyimi) içeren bir blok, yineleyici bloğu olarak adlandırılır.A block that contains one or more yield
statements (The yield statement) is called an iterator block. Yineleyici blokları, işlev üyelerini yineleyiciler (yineleyiciler) olarak uygulamak için kullanılır.Iterator blocks are used to implement function members as iterators (Iterators). Yineleyici blokları için bazı ek kısıtlamalar geçerlidir:Some additional restrictions apply to iterator blocks:
- Bir deyimin Yineleyici bloğunda görünmesi için derleme zamanı hatası
return
(ancakyield return
deyimlerine izin verilir).It is a compile-time error for areturn
statement to appear in an iterator block (butyield return
statements are permitted). - Bir yineleyici bloğunun güvenli olmayan bir bağlam (güvenli olmayan bağlamlar) içermesi için derleme zamanı hatası.It is a compile-time error for an iterator block to contain an unsafe context (Unsafe contexts). Bir yineleyici bloğu, bildirimi güvenli olmayan bir bağlamda iç içe yerleştirilmiş olsa bile her zaman güvenli bir bağlam tanımlar.An iterator block always defines a safe context, even when its declaration is nested in an unsafe context.
Ekstre listeleriStatement lists
* Deyim listesi _, sırayla yazılan bir veya daha fazla deyimden oluşur.A *statement list _ consists of one or more statements written in sequence. _Block * s (bloklar) ve switch_block s (Switch ifadesinde) içinde ifade listeleri oluşur.Statement lists occur in _block*s (Blocks) and in switch_block s (The switch statement).
statement_list
: statement+
;
Bir ifade listesi, denetim ilk ifadeye aktarılarak yürütülür.A statement list is executed by transferring control to the first statement. Ve denetimi bir deyimin bitiş noktasına ulaştığında, Denetim sonraki deyime aktarılır.When and if control reaches the end point of a statement, control is transferred to the next statement. Denetim, son deyimin bitiş noktasına ulaştığında denetim, ekstre listesinin bitiş noktasına aktarılır.When and if control reaches the end point of the last statement, control is transferred to the end point of the statement list.
Aşağıdakilerden en az biri doğru ise, bir ifade listesindeki deyime erişilebilir:A statement in a statement list is reachable if at least one of the following is true:
- İfade ilk ifadedir ve ekstre listesinin kendisi erişilebilir olur.The statement is the first statement and the statement list itself is reachable.
- Önceki deyimin bitiş noktasına ulaşılabilir.The end point of the preceding statement is reachable.
- İfade etiketli bir ifadedir ve etikete erişilebilir bir ifade tarafından başvuruluyor
goto
.The statement is a labeled statement and the label is referenced by a reachablegoto
statement.
Listedeki son deyimin bitiş noktası ulaşılabilir ise, bir ekstre listesinin bitiş noktası erişilebilir olur.The end point of a statement list is reachable if the end point of the last statement in the list is reachable.
Boş ifadeThe empty statement
Empty_statement hiçbir şey yapmaz.An empty_statement does nothing.
empty_statement
: ';'
;
Boş bir ifade, bir deyimin gerekli olduğu bir bağlamda gerçekleştirilecek bir işlem olmadığında kullanılır.An empty statement is used when there are no operations to perform in a context where a statement is required.
Boş bir deyimin yürütülmesi, denetimi yalnızca deyimin bitiş noktasına aktarır.Execution of an empty statement simply transfers control to the end point of the statement. Bu nedenle, boş deyimin erişilebilir olması halinde boş bir deyimin bitiş noktasına ulaşılabilir.Thus, the end point of an empty statement is reachable if the empty statement is reachable.
Boş bir ifade, while
null gövdesi olan bir ifade yazılırken kullanılabilir:An empty statement can be used when writing a while
statement with a null body:
bool ProcessMessage() {...}
void ProcessMessages() {
while (ProcessMessage())
;
}
Ayrıca, bir bloğun "" kapanışından hemen önce bir etiketi bildirmek için boş bir ifade kullanılabilir }
:Also, an empty statement can be used to declare a label just before the closing "}
" of a block:
void F() {
...
if (done) goto exit;
...
exit: ;
}
Etiketli deyimlerLabeled statements
Bir labeled_statement bir deyimin ön eki olarak belirtilmesine izin verir.A labeled_statement permits a statement to be prefixed by a label. Etiketli deyimlerde bloklara izin verilir, ancak gömülü deyimler olarak izin verilmez.Labeled statements are permitted in blocks, but are not permitted as embedded statements.
labeled_statement
: identifier ':' statement
;
Etiketli bir ifade, tanımlayıcı tarafından verilen ada sahip bir etiket bildirir.A labeled statement declares a label with the name given by the identifier. Bir etiketin kapsamı, iç içe geçmiş bloklar dahil olmak üzere, etiketin bildirildiği tüm bloğudur.The scope of a label is the whole block in which the label is declared, including any nested blocks. Çakışan kapsamlara sahip olmak için aynı ada sahip iki etiket için derleme zamanı hatasıdır.It is a compile-time error for two labels with the same name to have overlapping scopes.
Etiketin goto
kapsamı içinde deyimlerden (goto deyimi) bir etikete başvurulabilir.A label can be referenced from goto
statements (The goto statement) within the scope of the label. Bu goto
, deyimlerin blokları bloklar içinde ve blok dışında, ancak hiçbir şekilde bloklara aktarabileceği anlamına gelir.This means that goto
statements can transfer control within blocks and out of blocks, but never into blocks.
Etiketler kendi bildirim alanına sahiptir ve diğer tanımlayıcılarla karışmaz.Labels have their own declaration space and do not interfere with other identifiers. ÖrnekteThe example
int F(int x) {
if (x >= 0) goto x;
x = -x;
x: return x;
}
geçerli olur ve adı x
hem parametre hem de etiket olarak kullanır.is valid and uses the name x
as both a parameter and a label.
Etiketli bir deyimin yürütülmesi, etiketi izleyen deyimin yürütülmesi için tam olarak karşılık gelir.Execution of a labeled statement corresponds exactly to execution of the statement following the label.
Normal denetim akışı tarafından sağlanmış olan erişilebilirlik 'e ek olarak, etikete erişilebilir bir bildirimde başvuruluyorsa etiketli ifadeye erişilebilir goto
.In addition to the reachability provided by normal flow of control, a labeled statement is reachable if the label is referenced by a reachable goto
statement. (Özel durum: bir goto
ifade bir try
blok içeren bir içinde ise finally
ve etiketli ifade öğesinin dışındaysa ve try
bloğun bitiş noktası ulaşılamaz durumdaysa, finally
etiketlenmiş ifadeye bu goto
deyimden ulaşılamaz.)(Exception: If a goto
statement is inside a try
that includes a finally
block, and the labeled statement is outside the try
, and the end point of the finally
block is unreachable, then the labeled statement is not reachable from that goto
statement.)
Bildirim deyimleriDeclaration statements
Bir declaration_statement yerel bir değişkeni veya sabiti bildirir.A declaration_statement declares a local variable or constant. Bildirim deyimlerinin bloklara izin verilir, ancak gömülü deyimler olarak izin verilmez.Declaration statements are permitted in blocks, but are not permitted as embedded statements.
declaration_statement
: local_variable_declaration ';'
| local_constant_declaration ';'
;
Yerel değişken bildirimleriLocal variable declarations
Bir local_variable_declaration bir veya daha fazla yerel değişken bildirir.A local_variable_declaration declares one or more local variables.
local_variable_declaration
: local_variable_type local_variable_declarators
;
local_variable_type
: type
| 'var'
;
local_variable_declarators
: local_variable_declarator
| local_variable_declarators ',' local_variable_declarator
;
local_variable_declarator
: identifier
| identifier '=' local_variable_initializer
;
local_variable_initializer
: expression
| array_initializer
| local_variable_initializer_unsafe
;
Bir local_variable_declaration local_variable_type , bildirim tarafından tanıtılan değişkenlerin türünü doğrudan belirtir veya var
türün bir başlatıcıya göre çıkarsanı tanımlayıcı olduğunu gösterir.The local_variable_type of a local_variable_declaration either directly specifies the type of the variables introduced by the declaration, or indicates with the identifier var
that the type should be inferred based on an initializer. Türün ardından her biri yeni bir değişken sunan local_variable_declarator s listesi gelir.The type is followed by a list of local_variable_declarator s, each of which introduces a new variable. Bir local_variable_declarator , isteğe bağlı olarak, bir " =
" belirteci ve değişkenin başlangıç değerini veren bir local_variable_initializer gelen değişkeni belirten bir tanımlayıcıdan oluşur.A local_variable_declarator consists of an identifier that names the variable, optionally followed by an "=
" token and a local_variable_initializer that gives the initial value of the variable.
Yerel bir değişken bildirimi bağlamında, tanımlayıcı var bir bağlamsal anahtar sözcük (anahtar sözcük) olarak davranır. Local_variable_type olarak belirtildiğinde var
ve adlandırılmış hiçbir tür var
kapsamda olduğunda, bildirim örtük olarak yazılmış bir yerel değişken bildirimidir ve türü ilişkili Başlatıcı ifadesinin türünden çıkarsandır.In the context of a local variable declaration, the identifier var acts as a contextual keyword (Keywords).When the local_variable_type is specified as var
and no type named var
is in scope, the declaration is an implicitly typed local variable declaration, whose type is inferred from the type of the associated initializer expression. Örtük olarak yazılan yerel değişken bildirimleri aşağıdaki kısıtlamalara tabidir:Implicitly typed local variable declarations are subject to the following restrictions:
- Local_variable_declaration birden çok local_variable_declarator s içeremez.The local_variable_declaration cannot include multiple local_variable_declarator s.
- Local_variable_declarator bir local_variable_initializer içermelidir.The local_variable_declarator must include a local_variable_initializer.
- Local_variable_initializer bir ifade olmalıdır.The local_variable_initializer must be an expression.
- Başlatıcı ifadesi bir derleme zamanı türüne sahip olmalıdır.The initializer expression must have a compile-time type.
- Başlatıcı ifadesi , belirtilen değişkenin kendine başvuramazThe initializer expression cannot refer to the declared variable itself
Aşağıda, türü kesin olarak belirlenmiş geçersiz yerel değişken bildirimlerinin örnekleri verilmiştir:The following are examples of incorrect implicitly typed local variable declarations:
var x; // Error, no initializer to infer type from
var y = {1, 2, 3}; // Error, array initializer not permitted
var z = null; // Error, null does not have a type
var u = x => x + 1; // Error, anonymous functions do not have a type
var v = v++; // Error, initializer cannot refer to variable itself
Yerel bir değişkenin değeri bir simple_name (basit adlar) kullanılarak bir ifadede alınır ve yerel bir değişkenin değeri atama (atama işleçleri) kullanılarak değiştirilir.The value of a local variable is obtained in an expression using a simple_name (Simple names), and the value of a local variable is modified using an assignment (Assignment operators). Yerel değişken, değerinin alındığı her konumda kesinlikle atanmalıdır (kesin atama).A local variable must be definitely assigned (Definite assignment) at each location where its value is obtained.
Local_variable_declaration olarak 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 is the block in which the declaration occurs. Yerel değişkenin local_variable_declarator önündeki bir metinsel konumdaki yerel değişkene başvurabileceğiniz bir hatadır.It is an error to refer to a local variable in a textual position that precedes the local_variable_declarator of the local variable. Yerel bir değişken kapsamında, aynı ada sahip başka bir yerel değişken veya sabit bildirmek için derleme zamanı hatası vardır.Within the scope of a local variable, it is a compile-time error to declare another local variable or constant with the same name.
Birden çok değişken bildiren bir yerel değişken bildirimi, aynı türe sahip tek değişkenlerin birden çok bildirimi ile eşdeğerdir.A local variable declaration that declares multiple variables is equivalent to multiple declarations of single variables with the same type. Ayrıca, yerel bir değişken bildirimindeki bir değişken başlatıcısı, bildirimden hemen sonra eklenen bir atama bildirimine karşılık gelir.Furthermore, a variable initializer in a local variable declaration corresponds exactly to an assignment statement that is inserted immediately after the declaration.
ÖrnekteThe example
void F() {
int x = 1, y, z = x * 2;
}
tam olarak öğesine karşılık gelircorresponds exactly to
void F() {
int x; x = 1;
int y;
int z; z = x * 2;
}
Örtük olarak yazılmış bir yerel değişken bildiriminde, bildirildiği yerel değişkenin türü, değişkeni başlatmak için kullanılan ifadenin türüyle aynı olacak şekilde alınır.In an implicitly typed local variable declaration, the type of the local variable being declared is taken to be the same as the type of the expression used to initialize the variable. Örnek:For example:
var i = 5;
var s = "Hello";
var d = 1.0;
var numbers = new int[] {1, 2, 3};
var orders = new Dictionary<int,Order>();
Yukarıdaki örtük olarak yazılan yerel değişken bildirimleri aşağıdaki açıkça belirlenmiş bildirimlerle tam olarak eşdeğerdir:The implicitly typed local variable declarations above are precisely equivalent to the following explicitly typed declarations:
int i = 5;
string s = "Hello";
double d = 1.0;
int[] numbers = new int[] {1, 2, 3};
Dictionary<int,Order> orders = new Dictionary<int,Order>();
Yerel sabit bildirimlerLocal constant declarations
Bir local_constant_declaration bir veya daha fazla yerel sabiti bildirir.A local_constant_declaration declares one or more local constants.
local_constant_declaration
: 'const' type constant_declarators
;
constant_declarators
: constant_declarator (',' constant_declarator)*
;
constant_declarator
: identifier '=' constant_expression
;
Local_constant_declaration türü , bildirim tarafından tanıtılan sabitlerin türünü belirtir.The type of a local_constant_declaration specifies the type of the constants introduced by the declaration. Türün ardından her biri yeni bir sabit sunan constant_declarator s listesi bulunur.The type is followed by a list of constant_declarator s, each of which introduces a new constant. Constant_declarator , sabiti belirten bir tanımlayıcıdan , ardından bir " =
" belirteci ve ardından sabit değeri veren bir constant_expression (sabit deyimler) gelir.A constant_declarator consists of an identifier that names the constant, followed by an "=
" token, followed by a constant_expression (Constant expressions) that gives the value of the constant.
Yerel bir sabit bildirimin türü ve constant_expression , sabit üye bildirimiyle (sabitler) aynı kurallara uymalıdır.The type and constant_expression of a local constant declaration must follow the same rules as those of a constant member declaration (Constants).
Yerel bir sabitin değeri, simple_name (basit adlar) kullanılarak bir ifadede elde edilir.The value of a local constant is obtained in an expression using a simple_name (Simple names).
Yerel bir sabitin kapsamı, bildirimin gerçekleştiği bloğudur.The scope of a local constant is the block in which the declaration occurs. Constant_declarator önündeki bir metinsel konumda yerel bir Sabitte başvurmak hatadır.It is an error to refer to a local constant in a textual position that precedes its constant_declarator. Yerel bir sabit kapsamında, aynı ada sahip başka bir yerel değişken veya sabit bildirmek için derleme zamanı hatası vardır.Within the scope of a local constant, it is a compile-time error to declare another local variable or constant with the same name.
Birden çok sabiti bildiren yerel bir sabit bildirim, aynı türe sahip tek sabitlerin birden çok bildirimine eşdeğerdir.A local constant declaration that declares multiple constants is equivalent to multiple declarations of single constants with the same type.
İfade deyimleriExpression statements
Expression_statement belirli bir ifadeyi değerlendirir.An expression_statement evaluates a given expression. Varsa, ifade tarafından hesaplanan değer atılır.The value computed by the expression, if any, is discarded.
expression_statement
: statement_expression ';'
;
statement_expression
: invocation_expression
| null_conditional_invocation_expression
| object_creation_expression
| assignment
| post_increment_expression
| post_decrement_expression
| pre_increment_expression
| pre_decrement_expression
| await_expression
;
Tüm ifadelere deyim olarak izin verilmez.Not all expressions are permitted as statements. Özellikle, x + y
ve gibi x == 1
yalnızca bir değeri hesaplama (atılacak) gibi ifadeler, deyimler olarak izin verilmez.In particular, expressions such as x + y
and x == 1
that merely compute a value (which will be discarded), are not permitted as statements.
Bir expression_statement yürütülmesi içerilen ifadeyi değerlendirir ve sonra denetimi expression_statement bitiş noktasına aktarır.Execution of an expression_statement evaluates the contained expression and then transfers control to the end point of the expression_statement. Expression_statement bitiş noktası, expression_statement erişilebilir olduğunda erişilebilir.The end point of an expression_statement is reachable if that expression_statement is reachable.
Seçim deyimleriSelection statements
Seçim deyimleri, bazı deyimlerin değerine göre yürütme için bir dizi olası deyimden birini seçer.Selection statements select one of a number of possible statements for execution based on the value of some expression.
selection_statement
: if_statement
| switch_statement
;
If deyimiThe if statement
if
Deyimi, bir Boolean ifadesinin değerine göre yürütme için bir deyim seçer.The if
statement selects a statement for execution based on the value of a boolean expression.
if_statement
: 'if' '(' boolean_expression ')' embedded_statement
| 'if' '(' boolean_expression ')' embedded_statement 'else' embedded_statement
;
Bir else
bölüm, if
söz dizimi tarafından izin verilen, en yakın olan sözcüme ile ilişkilidir.An else
part is associated with the lexically nearest preceding if
that is allowed by the syntax. Bu nedenle, if
formun bir ifadesidirThus, an if
statement of the form
if (x) if (y) F(); else G();
eşdeğerdiris equivalent to
if (x) {
if (y) {
F();
}
else {
G();
}
}
Bir if
ifade aşağıdaki gibi yürütülür:An if
statement is executed as follows:
- Boolean_expression (Boolean ifadeler) değerlendirilir.The boolean_expression (Boolean expressions) is evaluated.
- Boolean ifadesi uygunsa
true
Denetim ilk eklenmiş ifadeye aktarılır.If the boolean expression yieldstrue
, control is transferred to the first embedded statement. Ve denetimi bu deyimin bitiş noktasına ulaştığında, denetim deyimin bitiş noktasına aktarılırif
.When and if control reaches the end point of that statement, control is transferred to the end point of theif
statement. - Boolean ifadesi varsa
false
ve birelse
bölüm varsa, denetim ikinci katıştırılmış deyime aktarılır.If the boolean expression yieldsfalse
and if anelse
part is present, control is transferred to the second embedded statement. Ve denetimi bu deyimin bitiş noktasına ulaştığında, denetim deyimin bitiş noktasına aktarılırif
.When and if control reaches the end point of that statement, control is transferred to the end point of theif
statement. - Boolean ifadesi varsa
false
ve birelse
bölüm yoksa, denetim deyimin bitiş noktasına aktarılırif
.If the boolean expression yieldsfalse
and if anelse
part is not present, control is transferred to the end point of theif
statement.
Deyim if
if
erişilebilir olduğunda ve Boolean ifadesinde sabit değer yoksa, bir deyimin ilk ekli deyimine erişilebilir false
.The first embedded statement of an if
statement is reachable if the if
statement is reachable and the boolean expression does not have the constant value false
.
Varsa, bir deyimin ikinci gömülü deyimi, if
if
deyimi erişilebilir olduğunda ve Boolean ifadesinde sabit değer yoksa erişilebilir olur true
.The second embedded statement of an if
statement, if present, is reachable if the if
statement is reachable and the boolean expression does not have the constant value true
.
Bir deyimin bitiş noktası, if
katıştırılmış deyimlerinden en az birinin bitiş noktası ulaşılabilir ise erişilebilir olur.The end point of an if
statement is reachable if the end point of at least one of its embedded statements is reachable. Ayrıca, if
else
if
deyim erişilebilir olduğunda ve Boole ifadesinde sabit değer yoksa, Bölüm içermeyen bir deyimin bitiş noktasına ulaşılamaz true
.In addition, the end point of an if
statement with no else
part is reachable if the if
statement is reachable and the boolean expression does not have the constant value true
.
Switch deyimleriThe switch statement
Switch deyimi, anahtar ifadesinin değerine karşılık gelen ilişkili bir anahtar etiketine sahip bir deyim listesini yürütmeye yönelik seçer.The switch statement selects for execution a statement list having an associated switch label that corresponds to the value of the switch expression.
switch_statement
: 'switch' '(' expression ')' switch_block
;
switch_block
: '{' switch_section* '}'
;
switch_section
: switch_label+ statement_list
;
switch_label
: 'case' constant_expression ':'
| 'default' ':'
;
Switch_statement , anahtar sözcüğünden oluşur ve ardından switch
parantez içine alınmış bir ifade (switch ifadesi olarak adlandırılır) ve ardından bir switch_block gelir.A switch_statement consists of the keyword switch
, followed by a parenthesized expression (called the switch expression), followed by a switch_block. Switch_block , küme ayraçları içine alınmış sıfır veya daha fazla switch_section oluşur.The switch_block consists of zero or more switch_section s, enclosed in braces. Her switch_section , bir veya daha fazla switch_label, ardından bir statement_list (ifade listesi) oluşur.Each switch_section consists of one or more switch_label s followed by a statement_list (Statement lists).
Bir deyimin yöneten türü , switch
switch ifadesi tarafından oluşturulur.The governing type of a switch
statement is established by the switch expression.
- Anahtar ifadesinin türü,,,,
sbyte
,,byte
,short
,ushort
int
uint
long
ulong
bool
,char
,string
ya da bir enum_type ya da bu türlerden birine karşılık gelen null yapılabilir türde ise, bu bildirimin yöneten türüdürswitch
.If the type of the switch expression issbyte
,byte
,short
,ushort
,int
,uint
,long
,ulong
,bool
,char
,string
, or an enum_type, or if it is the nullable type corresponding to one of these types, then that is the governing type of theswitch
statement. - Aksi halde, tam olarak bir Kullanıcı tanımlı örtük dönüştürme (Kullanıcı tanımlı dönüştürmeler), anahtar ifadesinin türünden,,,,,,,,,
sbyte
byte
short
ushort
int
uint
long
ulong
char
,string
veya, bu türlerden birine karşılık gelen null yapılabilir bir tür olmalıdır:,,,,,,,,, veya.Otherwise, exactly one user-defined implicit conversion (User-defined conversions) must exist from the type of the switch expression to one of the following possible governing types:sbyte
,byte
,short
,ushort
,int
,uint
,long
,ulong
,char
,string
, or, a nullable type corresponding to one of those types. - Aksi takdirde, böyle bir örtük dönüştürme yoksa veya birden fazla örtük dönüştürme varsa, bir derleme zamanı hatası oluşur.Otherwise, if no such implicit conversion exists, or if more than one such implicit conversion exists, a compile-time error occurs.
Her bir etiketin sabit ifadesi case
örtük olarak dönüştürülebilir bir değeri (örtük dönüştürmeler) deyimin yöneten türüne göre belirtmelidir switch
.The constant expression of each case
label must denote a value that is implicitly convertible (Implicit conversions) to the governing type of the switch
statement. Aynı deyimdeki iki veya daha fazla case
etiket switch
aynı sabit değeri belirtmediğinde bir derleme zamanı hatası oluşur.A compile-time error occurs if two or more case
labels in the same switch
statement specify the same constant value.
Switch ifadesinde en fazla bir default
etiket olabilir.There can be at most one default
label in a switch statement.
Bir switch
ifade aşağıdaki gibi yürütülür:A switch
statement is executed as follows:
- Anahtar ifadesi değerlendirilir ve yöneten türe dönüştürülür.The switch expression is evaluated and converted to the governing type.
- Aynı deyimdeki bir etikette belirtilen sabitlerden biri,
case
switch
switch ifadesinin değerine eşitse, denetim eşleşen etiketten sonraki deyim listesine aktarılırcase
.If one of the constants specified in acase
label in the sameswitch
statement is equal to the value of the switch expression, control is transferred to the statement list following the matchedcase
label. case
Aynı deyimdeki etiketlerde belirtilen sabitlerin hiçbiriswitch
anahtar ifadesinin değerine eşit değilse ve birdefault
etiket mevcutsa, Denetim etiketi izleyen deyim listesine aktarılırdefault
.If none of the constants specified incase
labels in the sameswitch
statement is equal to the value of the switch expression, and if adefault
label is present, control is transferred to the statement list following thedefault
label.case
Aynı deyimdeki etiketlerde belirtilen sabitlerin hiçbiriswitch
anahtar ifadesinin değerine eşit değilse ve birdefault
etiket yoksa, denetim deyimin bitiş noktasına aktarılırswitch
.If none of the constants specified incase
labels in the sameswitch
statement is equal to the value of the switch expression, and if nodefault
label is present, control is transferred to the end point of theswitch
statement.
Bir anahtar bölümünün ekstre listesinin bitiş noktasına ulaşılabiliyorsa, bir derleme zamanı hatası oluşur.If the end point of the statement list of a switch section is reachable, a compile-time error occurs. Bu, "hiçbir düşüş olmadan" kuralı olarak bilinir.This is known as the "no fall through" rule. ÖrnekteThe example
switch (i) {
case 0:
CaseZero();
break;
case 1:
CaseOne();
break;
default:
CaseOthers();
break;
}
, Switch bölümünün erişilebilir bir uç noktasına sahip olmadığı için geçerlidir.is valid because no switch section has a reachable end point. C ve C++ ' dan farklı olarak, bir switch bölümünün yürütülmesi bir sonraki anahtar bölümüne "düşmeyle" izin verilmez ve örnekUnlike C and C++, execution of a switch section is not permitted to "fall through" to the next switch section, and the example
switch (i) {
case 0:
CaseZero();
case 1:
CaseZeroOrOne();
default:
CaseAny();
}
derleme zamanı hatasına neden olur.results in a compile-time error. Bir switch bölümünün yürütülmesi başka bir anahtar bölümünün yürütülmesi tarafından izlenmesinin ardından açık goto case
veya bir goto default
deyimin kullanılması gerekir:When execution of a switch section is to be followed by execution of another switch section, an explicit goto case
or goto default
statement must be used:
switch (i) {
case 0:
CaseZero();
goto case 1;
case 1:
CaseZeroOrOne();
goto default;
default:
CaseAny();
break;
}
Switch_section birden çok etikete izin verilir.Multiple labels are permitted in a switch_section. ÖrnekteThe example
switch (i) {
case 0:
CaseZero();
break;
case 1:
CaseOne();
break;
case 2:
default:
CaseTwo();
break;
}
geçerli.is valid. Bu örnek, Etiketler case 2:
ve default:
aynı switch_section bir parçası olduğundan "hiçbir düşüş olmadan" kuralını ihlal etmez.The example does not violate the "no fall through" rule because the labels case 2:
and default:
are part of the same switch_section.
"Hiçbir düşüş yok" kuralı, deyimler yanlışlıkla atlandığında C ve C++ içinde oluşan ortak hata sınıflarını engeller break
.The "no fall through" rule prevents a common class of bugs that occur in C and C++ when break
statements are accidentally omitted. Ayrıca, bu kural nedeniyle, bir deyimin anahtar bölümleri deyimin davranışını etkilemeden rastgele bir şekilde yeniden switch
düzenlenebilir.In addition, because of this rule, the switch sections of a switch
statement can be arbitrarily rearranged without affecting the behavior of the statement. Örneğin, switch
Yukarıdaki deyimin bölümleri, deyimin davranışı etkilenmeden ters alınabilir:For example, the sections of the switch
statement above can be reversed without affecting the behavior of the statement:
switch (i) {
default:
CaseAny();
break;
case 1:
CaseZeroOrOne();
goto default;
case 0:
CaseZero();
goto case 1;
}
Bir switch bölümünün ifade listesi genellikle bir break
, veya ifadesinde sona erer goto case
goto default
, ancak bildirim listesinin ulaşılamaz bitiş noktasını işleyen herhangi bir yapı için izin verilir.The statement list of a switch section typically ends in a break
, goto case
, or goto default
statement, but any construct that renders the end point of the statement list unreachable is permitted. Örneğin, while
Boolean ifadesinin denetimindeki bir deyim, true
uç noktasına hiçbir şekilde ulaşamadığı bilinmektedir.For example, a while
statement controlled by the boolean expression true
is known to never reach its end point. Benzer şekilde, bir throw
veya return
deyimleri her zaman denetimi başka bir yere aktarır ve bitiş noktasına hiçbir zaman ulaşmaz.Likewise, a throw
or return
statement always transfers control elsewhere and never reaches its end point. Bu nedenle, aşağıdaki örnek geçerlidir:Thus, the following example is valid:
switch (i) {
case 0:
while (true) F();
case 1:
throw new ArgumentException();
case 2:
return;
}
Bir deyimin yöneten türü switch
tür olabilir string
.The governing type of a switch
statement may be the type string
. Örnek:For example:
void DoCommand(string command) {
switch (command.ToLower()) {
case "run":
DoRun();
break;
case "save":
DoSave();
break;
case "quit":
DoQuit();
break;
default:
InvalidCommand(command);
break;
}
}
Dize eşitlik işleçleri (dize eşitlik işleçleri) gibi, switch
deyim büyük/küçük harfe duyarlıdır ve yalnızca anahtar ifadesi dizesi bir etiket sabiti ile tam olarak eşleşiyorsa verilen bir anahtar bölümünü yürütür case
.Like the string equality operators (String equality operators), the switch
statement is case sensitive and will execute a given switch section only if the switch expression string exactly matches a case
label constant.
Bir deyimin yöneten türü olduğunda switch
string
, değere null
bir Case etiketi sabiti olarak izin verilir.When the governing type of a switch
statement is string
, the value null
is permitted as a case label constant.
Bir switch_block statement_list s, bildirim deyimlerini (bildirim deyimleri) içerebilir.The statement_list s of a switch_block may contain declaration statements (Declaration statements). Anahtar bloğunda belirtilen yerel bir değişken veya sabit kapsam, anahtar bloğudur.The scope of a local variable or constant declared in a switch block is the switch block.
Belirli bir switch bölümünün ifade listesi, switch
ifadeye ulaşılabiliyorsa ve aşağıdakilerden en az biri geçerliyse erişilebilir olur:The statement list of a given switch section is reachable if the switch
statement is reachable and at least one of the following is true:
- Switch ifadesi sabit olmayan bir değer.The switch expression is a non-constant value.
- Switch ifadesi, Switch bölümündeki bir etiketle eşleşen sabit bir değerdir
case
.The switch expression is a constant value that matches acase
label in the switch section. - Switch ifadesi herhangi bir etiketle eşleşmeyen sabit bir değerdir
case
ve Switch bölümüdefault
etiketi içerir.The switch expression is a constant value that doesn't match anycase
label, and the switch section contains thedefault
label. - Switch bölümünün anahtar etiketine erişilebilir
goto case
veya bildirim tarafından başvuruluyorgoto default
.A switch label of the switch section is referenced by a reachablegoto case
orgoto default
statement.
switch
Aşağıdakilerden en az biri doğru ise, bir deyimin bitiş noktasına ulaşılabilir:The end point of a switch
statement is reachable if at least one of the following is true:
switch
İfadebreak
, ifadesiyle çıkış yapan erişilebilir bir ifade içeriyorswitch
.Theswitch
statement contains a reachablebreak
statement that exits theswitch
statement.switch
Deyim erişilebilir, anahtar ifadesi sabit olmayan bir değer vedefault
etiket yok.Theswitch
statement is reachable, the switch expression is a non-constant value, and nodefault
label is present.switch
Deyim erişilebilir, anahtar ifadesi hiçbir etiketle eşleşmeyen bir sabit değerdircase
ve hiçbirdefault
etiket yoktur.Theswitch
statement is reachable, the switch expression is a constant value that doesn't match anycase
label, and nodefault
label is present.
Yineleme deyimleriIteration statements
Yineleme deyimleri, art arda gömülü bir deyimi yürütür.Iteration statements repeatedly execute an embedded statement.
iteration_statement
: while_statement
| do_statement
| for_statement
| foreach_statement
;
While ekstresiThe while statement
while
İfade, gömülü bir ifadeyi sıfır veya daha fazla kez koşullu olarak yürütür.The while
statement conditionally executes an embedded statement zero or more times.
while_statement
: 'while' '(' boolean_expression ')' embedded_statement
;
Bir while
ifade aşağıdaki gibi yürütülür:A while
statement is executed as follows:
- Boolean_expression (Boolean ifadeler) değerlendirilir.The boolean_expression (Boolean expressions) is evaluated.
- Boolean ifadesi uygunsa
true
Denetim katıştırılmış deyime aktarılır.If the boolean expression yieldstrue
, control is transferred to the embedded statement. Ve denetimi katıştırılmış deyimin bitiş noktasına ulaşırsa (muhtemelen bir deyimin yürütülmesindencontinue
), denetim deyimin başlangıcına aktarılırwhile
.When and if control reaches the end point of the embedded statement (possibly from execution of acontinue
statement), control is transferred to the beginning of thewhile
statement. - Boolean ifadesi uygunsa
false
Denetim deyimin bitiş noktasına aktarılırwhile
.If the boolean expression yieldsfalse
, control is transferred to the end point of thewhile
statement.
Bir deyimin gömülü ifadesinde while
, break
denetimi deyimin bitiş noktasına (Bu nedenle katıştırılmış deyimin sonuna kadar) aktarmak için bir ifade (kesme ekstresi) kullanılabilir while
, ve continue
denetimi katıştırılmış deyimin bitiş noktasına aktarmak için kullanılabilir (Bu nedenle deyimin başka biryinelemesi gerçekleştiriliyor) while
.Within the embedded statement of a while
statement, a break
statement (The break statement) may be used to transfer control to the end point of the while
statement (thus ending iteration of the embedded statement), and a continue
statement (The continue statement) may be used to transfer control to the end point of the embedded statement (thus performing another iteration of the while
statement).
while
while
Deyim erişilebilir olduğunda ve Boolean ifadesinde sabit değer yoksa, bir deyimin gömülü deyimine erişilebilir false
.The embedded statement of a while
statement is reachable if the while
statement is reachable and the boolean expression does not have the constant value false
.
while
Aşağıdakilerden en az biri doğru ise, bir deyimin bitiş noktasına ulaşılabilir:The end point of a while
statement is reachable if at least one of the following is true:
while
İfadebreak
, ifadesiyle çıkış yapan erişilebilir bir ifade içeriyorwhile
.Thewhile
statement contains a reachablebreak
statement that exits thewhile
statement.while
Deyimine erişilebilir ve Boole ifadesi sabit değere sahip değiltrue
.Thewhile
statement is reachable and the boolean expression does not have the constant valuetrue
.
Do ekstresiThe do statement
do
İfade, gömülü bir ifadeyi bir veya daha fazla kez koşullu olarak yürütür.The do
statement conditionally executes an embedded statement one or more times.
do_statement
: 'do' embedded_statement 'while' '(' boolean_expression ')' ';'
;
Bir do
ifade aşağıdaki gibi yürütülür:A do
statement is executed as follows:
- Denetim katıştırılmış deyime aktarılır.Control is transferred to the embedded statement.
- Ve denetimi katıştırılmış deyimin bitiş noktasına ulaşırsa (muhtemelen bir deyimin yürütülmesinden
continue
) Boolean_expression (Boolean ifadeler) değerlendirilir.When and if control reaches the end point of the embedded statement (possibly from execution of acontinue
statement), the boolean_expression (Boolean expressions) is evaluated. Boolean ifadesi uygunsatrue
Denetim deyimin başlangıcına aktarılırdo
.If the boolean expression yieldstrue
, control is transferred to the beginning of thedo
statement. Aksi takdirde denetim, deyimin bitiş noktasına aktarılırdo
.Otherwise, control is transferred to the end point of thedo
statement.
Bir deyimin gömülü ifadesinde do
, break
denetimi deyimin bitiş noktasına aktarmak için bir ifade (Break bildirisi) kullanılabilir do
(Bu nedenle gömülü deyimin yinelemesi sona eriyor) ve continue
denetimi katıştırılmış deyimin bitiş noktasına aktarmak için bir ifade (Continue deyimleri) kullanılabilir.Within the embedded statement of a do
statement, a break
statement (The break statement) may be used to transfer control to the end point of the do
statement (thus ending iteration of the embedded statement), and a continue
statement (The continue statement) may be used to transfer control to the end point of the embedded statement.
do
Deyimden ulaşılabilir olduğunda bir deyimin gömülü ifadesine ulaşılabilir do
.The embedded statement of a do
statement is reachable if the do
statement is reachable.
do
Aşağıdakilerden en az biri doğru ise, bir deyimin bitiş noktasına ulaşılabilir:The end point of a do
statement is reachable if at least one of the following is true:
do
İfadebreak
, ifadesiyle çıkış yapan erişilebilir bir ifade içeriyordo
.Thedo
statement contains a reachablebreak
statement that exits thedo
statement.- Katıştırılmış deyimin bitiş noktasına ulaşılabilir ve Boole ifadesi sabit değere sahip değil
true
.The end point of the embedded statement is reachable and the boolean expression does not have the constant valuetrue
.
For deyimleriThe for statement
for
Deyimi, bir dizi başlatma ifadesi değerlendirir ve sonra bir koşul true olduğunda, gömülü bir deyimi tekrar tekrar yürütür ve bir dizi yineleme ifadesini değerlendirir.The for
statement evaluates a sequence of initialization expressions and then, while a condition is true, repeatedly executes an embedded statement and evaluates a sequence of iteration expressions.
for_statement
: 'for' '(' for_initializer? ';' for_condition? ';' for_iterator? ')' embedded_statement
;
for_initializer
: local_variable_declaration
| statement_expression_list
;
for_condition
: boolean_expression
;
for_iterator
: statement_expression_list
;
statement_expression_list
: statement_expression (',' statement_expression)*
;
Varsa for_initializer, virgülle ayrılmış bir local_variable_declaration (yerel değişken bildirimleri) ya da bir statement_expression s (ifade deyimleri) listesinden oluşur.The for_initializer, if present, consists of either a local_variable_declaration (Local variable declarations) or a list of statement_expression s (Expression statements) separated by commas. Bir for_initializer tarafından belirtilen bir yerel değişkenin kapsamı, değişken için local_variable_declarator başlar ve ekli deyimin sonuna genişletilir.The scope of a local variable declared by a for_initializer starts at the local_variable_declarator for the variable and extends to the end of the embedded statement. Kapsam for_condition ve for_iterator içerir.The scope includes the for_condition and the for_iterator.
Varsa for_condition, bir Boolean_expression (Boolean ifadeler) olmalıdır.The for_condition, if present, must be a boolean_expression (Boolean expressions).
Varsa for_iterator, virgülle ayrılmış Statement_expression s (ifade deyimleri) listesinden oluşur.The for_iterator, if present, consists of a list of statement_expression s (Expression statements) separated by commas.
A for deyimleri aşağıdaki gibi yürütülür:A for statement is executed as follows:
- Bir for_initializer varsa, değişken başlatıcıları veya deyim ifadeleri yazıldığı sırada yürütülür.If a for_initializer is present, the variable initializers or statement expressions are executed in the order they are written. Bu adım yalnızca bir kez gerçekleştirilir.This step is only performed once.
- Bir for_condition varsa, değerlendirilir.If a for_condition is present, it is evaluated.
- For_condition yoksa veya değerlendirme uygunsa
true
Denetim katıştırılmış deyime aktarılır.If the for_condition is not present or if the evaluation yieldstrue
, control is transferred to the embedded statement. Ve denetimi katıştırılmış deyimin bitiş noktasına ulaştığında (büyük olasılıkla bir deyimin yürütülmesindencontinue
), varsa for_iterator ifadeleri sırayla değerlendirilir ve yukarıdaki adımda for_condition değerlendirmesiyle başlayarak başka bir yineleme gerçekleştirilir.When and if control reaches the end point of the embedded statement (possibly from execution of acontinue
statement), the expressions of the for_iterator, if any, are evaluated in sequence, and then another iteration is performed, starting with evaluation of the for_condition in the step above. - For_condition varsa ve değerlendirme ise
false
, denetim deyimin bitiş noktasına aktarılırfor
.If the for_condition is present and the evaluation yieldsfalse
, control is transferred to the end point of thefor
statement.
Bir deyimin Embedded ifadesinde for
, bir break
ifade (kesme ekstresi), denetimi deyimin bitiş noktasına aktarmak için kullanılabilir for
(Bu nedenle, katıştırılmış deyimin yinelemesi sona eriyor) ve bir continue
deyimin (devam eden bildiri) katıştırılmış deyimin bitiş noktasına aktarımı için kullanılabilir (Bu nedenle, for_iterator ve for
for_condition ile başlayan deyimin başka bir yinelemesini gerçekleştirerek).Within the embedded statement of a for
statement, a break
statement (The break statement) may be used to transfer control to the end point of the for
statement (thus ending iteration of the embedded statement), and a continue
statement (The continue statement) may be used to transfer control to the end point of the embedded statement (thus executing the for_iterator and performing another iteration of the for
statement, starting with the for_condition).
for
Aşağıdakilerden biri doğruysa, bir deyimin gömülü ifadesine ulaşılabilir:The embedded statement of a for
statement is reachable if one of the following is true:
for
İfadeye ulaşılabilir ve for_condition yok.Thefor
statement is reachable and no for_condition is present.for
İfadeye erişilebilir ve bir for_condition var ve sabit değere sahip değilfalse
.Thefor
statement is reachable and a for_condition is present and does not have the constant valuefalse
.
for
Aşağıdakilerden en az biri doğru ise, bir deyimin bitiş noktasına ulaşılabilir:The end point of a for
statement is reachable if at least one of the following is true:
for
İfadebreak
, ifadesiyle çıkış yapan erişilebilir bir ifade içeriyorfor
.Thefor
statement contains a reachablebreak
statement that exits thefor
statement.for
İfadeye erişilebilir ve bir for_condition var ve sabit değere sahip değiltrue
.Thefor
statement is reachable and a for_condition is present and does not have the constant valuetrue
.
Foreach ifadesiThe foreach statement
İfade, koleksiyonun foreach
öğelerinin her öğesi için gömülü bir ifade yürüten bir koleksiyonun öğelerini numaralandırır.The foreach
statement enumerates the elements of a collection, executing an embedded statement for each element of the collection.
foreach_statement
: 'foreach' '(' local_variable_type identifier 'in' expression ')' embedded_statement
;
Deyimin türü ve tanımlayıcısı foreach
deyimin *yineleme değişkenini bildirir.The type and identifier of a foreach
statement declare the *iteration variable _ of the statement. Tanımlayıcı, var
_local_variable_type * olarak verilirse ve adında bir tür varsa var
, yineleme değişkeni örtük olarak yazılmış bir yineleme değişkeni olarak adlandırılır ve türü, foreach
aşağıda belirtildiği gibi deyimin öğe türü olarak alınır.If the var
identifier is given as the _local_variable_type*, and no type named var
is in scope, the iteration variable is said to be an implicitly typed iteration variable, and its type is taken to be the element type of the foreach
statement, as specified below. Yineleme değişkeni, katıştırılmış deyimin kapsamını genişleten bir salt okunurdur yerel değişkene karşılık gelir.The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement. Bir deyimin yürütülmesi sırasında foreach
yineleme değişkeni, bir yinelemenin Şu anda gerçekleştirildiği koleksiyon öğesini temsil eder.During execution of a foreach
statement, the iteration variable represents the collection element for which an iteration is currently being performed. Katıştırılmış deyimin yineleme değişkenini (atama ya da ++
ve --
işleçler aracılığıyla) değiştirmeye veya yineleme değişkenini bir veya parametresi olarak geçirmeye çalışırsa bir derleme zamanı hatası oluşur ref
out
.A compile-time error occurs if the embedded statement attempts to modify the iteration variable (via assignment or the ++
and --
operators) or pass the iteration variable as a ref
or out
parameter.
Aşağıda, kısaltma için,, IEnumerable
IEnumerator
IEnumerable<T>
ve IEnumerator<T>
ad alanları ve içindeki ilgili türlere bakın System.Collections
System.Collections.Generic
.In the following, for brevity, IEnumerable
, IEnumerator
, IEnumerable<T>
and IEnumerator<T>
refer to the corresponding types in the namespaces System.Collections
and System.Collections.Generic
.
Foreach deyiminin derleme zamanı işleme, ifadenin koleksiyon türü _, _Numaralandırıcı türü*_ ve _ öğe türü * öğesini belirler.The compile-time processing of a foreach statement first determines the collection type _, _enumerator type_ and _ element type of the expression. Bu belirleme işlemi aşağıdaki gibi gerçekleştirilir:This determination proceeds as follows:
X
İfade türü bir dizi türü ise, arabirime bir örtük başvuru dönüştürmesi vardırX
IEnumerable
(System.Array
Bu arabirimden bu yana).If the typeX
of expression is an array type then there is an implicit reference conversion fromX
to theIEnumerable
interface (sinceSystem.Array
implements this interface). Koleksiyon türü _IEnumerable
arabirim, _Numaralandırıcı türü_IEnumerator
arayüztür ve _ öğesi türü dizi türünün öğe türüdürX
.The collection type _ is theIEnumerable
interface, the _enumerator type_ is theIEnumerator
interface and the _ element type is the element type of the array typeX
.X
İfadenin türüdynamic
daha sonra deyimdenIEnumerable
arabirime (örtük dinamik dönüştürmeler) örtük bir dönüşüm varsa.If the typeX
of expression isdynamic
then there is an implicit conversion from expression to theIEnumerable
interface (Implicit dynamic conversions). Koleksiyon türü _,IEnumerable
arabirimdir ve _Numaralandırıcı türüdür*_IEnumerator
.The collection type _ is theIEnumerable
interface and the _enumerator type*_ is theIEnumerator
interface.var
Tanımlayıcı _local_variable_type * olarak verilirse, öğe türü ise,dynamic
Aksi durumdaobject
.If thevar
identifier is given as the _local_variable_type* then the element type isdynamic
, otherwise it isobject
.Aksi takdirde, türün
X
uygun bir yönteme sahip olup olmadığını saptayınGetEnumerator
:Otherwise, determine whether the typeX
has an appropriateGetEnumerator
method:X
TanımlayıcıGetEnumerator
ve tür bağımsız değişkeni olmayan tür üzerinde üye araması gerçekleştirin.Perform member lookup on the typeX
with identifierGetEnumerator
and no type arguments. Üye arama bir eşleşme oluşturmuyorsa veya bir belirsizlik üretir ya da bir yöntem grubu olmayan bir eşleşme üretirse, aşağıda açıklandığı gibi sıralanabilir bir arabirim olup olmadığını kontrol edin.If the member lookup does not produce a match, or it produces an ambiguity, or produces a match that is not a method group, check for an enumerable interface as described below. Üye arama yöntemi bir yöntem grubu veya eşleşme dışında bir şey üretirse bir uyarı verilmesi önerilir.It is recommended that a warning be issued if member lookup produces anything except a method group or no match.- Elde edilen yöntem grubunu ve boş bir bağımsız değişken listesini kullanarak aşırı yükleme çözümlemesi gerçekleştirin.Perform overload resolution using the resulting method group and an empty argument list. Aşırı yükleme çözümlemesi uygulanabilir bir yöntem olmadan sonuçlanırsa, belirsizliğe neden olur veya tek bir en iyi yöntemle sonuçlanır, ancak bu yöntem statik veya genel değil, aşağıda açıklandığı gibi sıralanabilir bir arabirim olup olmadığını kontrol edin.If overload resolution results in no applicable methods, results in an ambiguity, or results in a single best method but that method is either static or not public, check for an enumerable interface as described below. Aşırı yükleme çözümlemesi, belirsiz bir ortak örnek yöntemi veya uygulanabilir Yöntemler dışında bir şey üretirse bir uyarı verilmesi önerilir.It is recommended that a warning be issued if overload resolution produces anything except an unambiguous public instance method or no applicable methods.
- Yöntemin dönüş türü
E
GetEnumerator
bir sınıf, yapı veya arabirim türü değilse, bir hata oluşturulur ve başka bir adım alınmaz.If the return typeE
of theGetEnumerator
method is not a class, struct or interface type, an error is produced and no further steps are taken. - Üye arama,
E
tanımlayıcısıCurrent
ve tür bağımsız değişkenleri olmadan üzerinde gerçekleştirilir.Member lookup is performed onE
with the identifierCurrent
and no type arguments. Üye arama hiçbir eşleşme oluşturmazsa, sonuç bir hatadır veya sonuç, okumaya izin veren bir ortak örnek özelliği dışında bir hata oluşturulur ve başka hiçbir adım alınmaz.If the member lookup produces no match, the result is an error, or the result is anything except a public instance property that permits reading, an error is produced and no further steps are taken. - Üye arama,
E
tanımlayıcısıMoveNext
ve tür bağımsız değişkenleri olmadan üzerinde gerçekleştirilir.Member lookup is performed onE
with the identifierMoveNext
and no type arguments. Üye arama hiçbir eşleşme oluşturmazsa, sonuç bir hatadır veya sonuç bir yöntem grubu dışında bir hata üretiyorsa, başka bir adım alınmaz.If the member lookup produces no match, the result is an error, or the result is anything except a method group, an error is produced and no further steps are taken. - Aşırı yükleme çözümlemesi, metot grubunda boş bir bağımsız değişken listesiyle gerçekleştirilir.Overload resolution is performed on the method group with an empty argument list. Aşırı yükleme çözümlemesi uygulanabilir bir yöntem olmadan sonuçlanırsa, bir belirsizliğe neden olur ya da tek bir en iyi yöntem ile sonuçlanır, ancak bu yöntem statik veya genel değildir veya dönüş türü değildir
bool
, bir hata üretilir ve başka bir adım alınmaz.If overload resolution results in no applicable methods, results in an ambiguity, or results in a single best method but that method is either static or not public, or its return type is notbool
, an error is produced and no further steps are taken. - Koleksiyon türü _,
X
_Numaralandırıcı türü*_E
ve _ *öğe türü**,Current
özelliğin türüdür.The collection type _ isX
, the _enumerator type_ isE
, and the _ element type is the type of theCurrent
property.
Aksi takdirde, sıralanabilir bir arabirim olup olmadığını kontrol edin:Otherwise, check for an enumerable interface:
Ti
' Den örtük bir dönüştürme olan tüm türler arasındaX
IEnumerable<Ti>
, olmayan bir benzersiz tür vardırT
ve 'T
dynamic
den ' a örtük bir dönüştürme söz konusu olduğunda,Ti
IEnumerable<T>
IEnumerable<Ti>
koleksiyon türü _,IEnumerable<T>
_Numaralandırıcı türü_ arayüztürIEnumerator<T>
ve _ öğe türü olurT
.If among all the typesTi
for which there is an implicit conversion fromX
toIEnumerable<Ti>
, there is a unique typeT
such thatT
is notdynamic
and for all the otherTi
there is an implicit conversion fromIEnumerable<T>
toIEnumerable<Ti>
, then the collection type _ is the interfaceIEnumerable<T>
, the _enumerator type_ is the interfaceIEnumerator<T>
, and the _ element type isT
.- Aksi takdirde, böyle birden çok tür varsa
T
, bir hata oluşturulur ve başka bir adım alınmaz.Otherwise, if there is more than one such typeT
, then an error is produced and no further steps are taken. - Aksi halde, arabirimine örtük bir dönüşüm varsa
X
System.Collections.IEnumerable
, koleksiyon türü _ Bu arabirimdir, _Numaralandırıcı türü arayüztür_System.Collections.IEnumerator
ve _ öğe türü olurobject
.Otherwise, if there is an implicit conversion fromX
to theSystem.Collections.IEnumerable
interface, then the collection type _ is this interface, the _enumerator type_ is the interfaceSystem.Collections.IEnumerator
, and the _ element type isobject
. - Aksi halde, bir hata oluşturulur ve başka bir adım alınmaz.Otherwise, an error is produced and no further steps are taken.
Yukarıdaki adımlar başarılı olursa, kesin bir şekilde koleksiyon türü C
, Numaralandırıcı türü E
ve öğe türü üretir T
.The above steps, if successful, unambiguously produce a collection type C
, enumerator type E
and element type T
. Formun foreach ifadesiA foreach statement of the form
foreach (V v in x) embedded_statement
daha sonra şu şekilde genişletilir:is then expanded to:
{
E e = ((C)(x)).GetEnumerator();
try {
while (e.MoveNext()) {
V v = (V)(T)e.Current;
embedded_statement
}
}
finally {
... // Dispose e
}
}
Değişken, e
ifade x
veya katıştırılmış deyim ya da programın başka bir kaynak kodu için görünür veya erişilebilir değil.The variable e
is not visible to or accessible to the expression x
or the embedded statement or any other source code of the program. Değişken, v
gömülü ifadede salt okunurdur.The variable v
is read-only in the embedded statement. (Öğe türü) öğesinden (foreach deyimindeki local_variable_type) açık bir dönüştürme (Açık dönüştürmeler) yoksa T
V
, bir hata oluşturulur ve başka bir adım alınmaz.If there is not an explicit conversion (Explicit conversions) from T
(the element type) to V
(the local_variable_type in the foreach statement), an error is produced and no further steps are taken. x
Değeri varsa null
, System.NullReferenceException
çalışma zamanında bir oluşturulur.If x
has the value null
, a System.NullReferenceException
is thrown at run-time.
Davranışın yukarıdaki genişlemeyle tutarlı olduğu sürece, bir uygulamanın belirli bir foreach-deyimin farklı şekilde uygulanmasına izin verilir; Örneğin performans nedenleriyle.An implementation is permitted to implement a given foreach-statement differently, e.g. for performance reasons, as long as the behavior is consistent with the above expansion.
v
While döngüsünün içindeki yerleşimi, embedded_statement oluşan herhangi bir anonim işlev tarafından nasıl yakalandığından önemlidir.The placement of v
inside the while loop is important for how it is captured by any anonymous function occurring in the embedded_statement.
Örnek:For example:
int[] values = { 7, 9, 13 };
Action f = null;
foreach (var value in values)
{
if (f == null) f = () => Console.WriteLine("First value: " + value);
}
f();
v
While döngüsünün dışında bildirilirse, bu, tüm yinelemeler arasında paylaşılır ve for döngüsünden sonraki değeri son değer olacaktır, 13
Bu, ' nin f
çağrılma değeridir.If v
was declared outside of the while loop, it would be shared among all iterations, and its value after the for loop would be the final value, 13
, which is what the invocation of f
would print. Bunun yerine, her yineleme kendi değişkenine sahip olduğundan v
, ilk yinelemede tarafından yakalanan tek f
şey değeri tutmaya devam eder 7
, bu, yazdırılacak şeydir.Instead, because each iteration has its own variable v
, the one captured by f
in the first iteration will continue to hold the value 7
, which is what will be printed. (Note: önceki C# sürümleri v
while döngüsünün dışında bildirilmiştir.)(Note: earlier versions of C# declared v
outside of the while loop.)
Finally bloğunun gövdesi aşağıdaki adımlara göre oluşturulur:The body of the finally block is constructed according to the following steps:
Arabiriminden örtülü bir dönüşüm varsa
E
System.IDisposable
,If there is an implicit conversion fromE
to theSystem.IDisposable
interface, thenE
Null yapılamayan bir değer türü ise finally yan tümcesi, ' nin anlamsal eşdeğerine genişletilir:IfE
is a non-nullable value type then the finally clause is expanded to the semantic equivalent of:finally { ((System.IDisposable)e).Dispose(); }
Aksi halde finally yan tümcesi anlam eşdeğerine genişletilir:Otherwise the finally clause is expanded to the semantic equivalent of:
finally { if (e != null) ((System.IDisposable)e).Dispose(); }
E
bir değer türü veya bir değer türüne örneklenmiş tür parametresi olması dışında, ' ın ' a dönüştürme işlemi,e
System.IDisposable
kutulamayı oluşmasına neden olmaz.except that ifE
is a value type, or a type parameter instantiated to a value type, then the cast ofe
toSystem.IDisposable
will not cause boxing to occur.Aksi halde,
E
korumalı bir tür ise finally yan tümcesi boş bir bloğa genişletilir:Otherwise, ifE
is a sealed type, the finally clause is expanded to an empty block:finally { }
Aksi takdirde, finally yan tümcesi şu şekilde genişletilir:Otherwise, the finally clause is expanded to:
finally { System.IDisposable d = e as System.IDisposable; if (d != null) d.Dispose(); }
Yerel değişken,
d
herhangi bir kullanıcı koduna görünmez veya erişemez.The local variabled
is not visible to or accessible to any user code. Özellikle, kapsamı finally bloğunu içeren başka herhangi bir değişkenle çakışmaz.In particular, it does not conflict with any other variable whose scope includes the finally block.
foreach
Bir dizinin öğelerinin taşındığı sıra şu şekildedir: tek boyutlu diziler öğeleri, dizin ile başlayıp dizinle biten Dizin sırasına göre artırılır 0
Length - 1
.The order in which foreach
traverses the elements of an array, is as follows: For single-dimensional arrays elements are traversed in increasing index order, starting with index 0
and ending with index Length - 1
. Çok boyutlu diziler için öğelere, en sağdaki boyutun dizinlerinin önce artması, sonra bir sonraki sol boyutun ve bu şekilde sol tarafta olması gerekir.For multi-dimensional arrays, elements are traversed such that the indices of the rightmost dimension are increased first, then the next left dimension, and so on to the left.
Aşağıdaki örnek, her bir değeri öğe sırasıyla iki boyutlu bir dizide yazdırır:The following example prints out each value in a two-dimensional array, in element order:
using System;
class Test
{
static void Main() {
double[,] values = {
{1.2, 2.3, 3.4, 4.5},
{5.6, 6.7, 7.8, 8.9}
};
foreach (double elementValue in values)
Console.Write("{0} ", elementValue);
Console.WriteLine();
}
}
Oluşturulan çıkış aşağıdaki gibidir:The output produced is as follows:
1.2 2.3 3.4 4.5 5.6 6.7 7.8 8.9
ÖrnekteIn the example
int[] numbers = { 1, 3, 5, 7, 9 };
foreach (var n in numbers) Console.WriteLine(n);
türü olarak n
algılanır int
, öğesinin öğesi türü numbers
.the type of n
is inferred to be int
, the element type of numbers
.
Atlama deyimleriJump statements
Geçiş deyimleri koşulsuz olmayan aktarma denetimi.Jump statements unconditionally transfer control.
jump_statement
: break_statement
| continue_statement
| goto_statement
| return_statement
| throw_statement
;
Bir atma bildirimine aktarma denetimi, atlamanın hedefi olarak adlandırılır.The location to which a jump statement transfers control is called the target of the jump statement.
Bir blok içinde bir atdeyim oluştuğunda ve bu sıçrama ifadesinin hedefi o bloğun dışında olduğunda, atlamanın bloğundan Çıkış olarak söylenir.When a jump statement occurs within a block, and the target of that jump statement is outside that block, the jump statement is said to exit the block. Bir atlamayla denetimi bir bloğun dışına aktarabileceği sürece denetim bir bloğa hiçbir şekilde aktarılmaz.While a jump statement may transfer control out of a block, it can never transfer control into a block.
Sıçrama deyimlerinin yürütülmesi, aradaki deyimlerin varlığı tarafından karmaşıktır try
.Execution of jump statements is complicated by the presence of intervening try
statements. Bu tür deyimler yokluğunda try
, bir sıçrama deyimi, denetimi bir atlamanın hedefine koşulsuz olarak aktarır.In the absence of such try
statements, a jump statement unconditionally transfers control from the jump statement to its target. Bu tür bir araya giren try
deyimler varsa, yürütme daha karmaşıktır.In the presence of such intervening try
statements, execution is more complex. Atif deyim ilişkili bloklarla bir veya daha fazla try
finally
bloktan çıkıldığında denetim başlangıçta en finally
içteki deyimin bloğuna aktarılır try
.If the jump statement exits one or more try
blocks with associated finally
blocks, control is initially transferred to the finally
block of the innermost try
statement. Ve denetimi bir bloğun bitiş noktasına ulaştığında finally
, Denetim finally
sonraki kapsayan deyimin bloğuna aktarılır try
.When and if control reaches the end point of a finally
block, control is transferred to the finally
block of the next enclosing try
statement. Bu işlem, finally
tüm araya try
eklenen deyimlerin blokları yürütülene kadar yinelenir.This process is repeated until the finally
blocks of all intervening try
statements have been executed.
ÖrnekteIn the example
using System;
class Test
{
static void Main() {
while (true) {
try {
try {
Console.WriteLine("Before break");
break;
}
finally {
Console.WriteLine("Innermost finally block");
}
}
finally {
Console.WriteLine("Outermost finally block");
}
}
Console.WriteLine("After break");
}
}
finally
iki deyimle ilişkili bloklar, try
Denetim, sıçrama ifadesinin hedefine aktarılmadan önce yürütülür.the finally
blocks associated with two try
statements are executed before control is transferred to the target of the jump statement.
Oluşturulan çıkış aşağıdaki gibidir:The output produced is as follows:
Before break
Innermost finally block
Outermost finally block
After break
Break ekstresiThe break statement
break
İfade en yakın kapsayan switch
,,, while
, do
for
veya ifadesiyle çıkar foreach
.The break
statement exits the nearest enclosing switch
, while
, do
, for
, or foreach
statement.
break_statement
: 'break' ';'
;
Bir deyimin hedefi, break
en yakın kapsayan switch
,,,, while
do
for
veya foreach
ifadesinin bitiş noktasıdır.The target of a break
statement is the end point of the nearest enclosing switch
, while
, do
, for
, or foreach
statement. Bir break
ifade bir,,, switch
while
do
for
veya foreach
ifadesiyle çevrelenemez, derleme zamanı hatası oluşur.If a break
statement is not enclosed by a switch
, while
, do
, for
, or foreach
statement, a compile-time error occurs.
Birden çok switch
, while
, do
, for
, veya foreach
deyimleri birbirine yuvalandığı zaman, bir break
deyim yalnızca en içteki deyim için geçerlidir.When multiple switch
, while
, do
, for
, or foreach
statements are nested within each other, a break
statement applies only to the innermost statement. Birden çok iç içe düzeylerdeki denetimi aktarmak için bir goto
deyimin (goto deyimidir) kullanılması gerekir.To transfer control across multiple nesting levels, a goto
statement (The goto statement) must be used.
Bir break
ifade bir finally
bloğundan (TRY ifadesiyle) çıkabilir.A break
statement cannot exit a finally
block (The try statement). Bir break
blok içinde bir ifade gerçekleştiğinde finally
, break
deyimin hedefi aynı blok içinde olmalıdır finally
; Aksi takdirde, bir derleme zamanı hatası oluşur.When a break
statement occurs within a finally
block, the target of the break
statement must be within the same finally
block; otherwise, a compile-time error occurs.
Bir break
ifade aşağıdaki gibi yürütülür:A break
statement is executed as follows:
break
İfade ilişkili bloklarla bir veya daha fazlatry
finally
bloktan çıkıldığında denetim başlangıçta enfinally
içteki deyimin bloğuna aktarılırtry
.If thebreak
statement exits one or moretry
blocks with associatedfinally
blocks, control is initially transferred to thefinally
block of the innermosttry
statement. Ve denetimi bir bloğun bitiş noktasına ulaştığındafinally
, Denetimfinally
sonraki kapsayan deyimin bloğuna aktarılırtry
.When and if control reaches the end point of afinally
block, control is transferred to thefinally
block of the next enclosingtry
statement. Bu işlem,finally
tüm arayatry
eklenen deyimlerin blokları yürütülene kadar yinelenir.This process is repeated until thefinally
blocks of all interveningtry
statements have been executed.- Denetim, deyimin hedefine aktarılır
break
.Control is transferred to the target of thebreak
statement.
Bir break
ifade denetimi başka bir yerde bir yere aktarmadığı için, bir deyimin bitiş noktasına break
hiçbir şekilde ulaşılamıyor.Because a break
statement unconditionally transfers control elsewhere, the end point of a break
statement is never reachable.
Continue ekstresiThe continue statement
Bu continue
ifade, en yakın kapsayan while
, do
, for
, veya bildiriminin yeni bir yinelemesini başlatır foreach
.The continue
statement starts a new iteration of the nearest enclosing while
, do
, for
, or foreach
statement.
continue_statement
: 'continue' ';'
;
Bir deyimin hedefi, continue
en yakın kapsayan while
, do
, for
, veya bildiriminin gömülü ifadesinin bitiş noktasıdır foreach
.The target of a continue
statement is the end point of the embedded statement of the nearest enclosing while
, do
, for
, or foreach
statement. Bir continue
ifade,,, while
do
for
veya foreach
ifadesiyle çevrelenemez, derleme zamanı hatası oluşur.If a continue
statement is not enclosed by a while
, do
, for
, or foreach
statement, a compile-time error occurs.
Birden çok while
, do
, for
, veya foreach
deyimleri birbirine yuvalandığı zaman, bir continue
deyim yalnızca en içteki deyim için geçerlidir.When multiple while
, do
, for
, or foreach
statements are nested within each other, a continue
statement applies only to the innermost statement. Birden çok iç içe düzeylerdeki denetimi aktarmak için bir goto
deyimin (goto deyimidir) kullanılması gerekir.To transfer control across multiple nesting levels, a goto
statement (The goto statement) must be used.
Bir continue
ifade bir finally
bloğundan (TRY ifadesiyle) çıkabilir.A continue
statement cannot exit a finally
block (The try statement). Bir continue
blok içinde bir ifade gerçekleştiğinde finally
, continue
deyimin hedefi aynı blok içinde olmalıdır finally
; Aksi takdirde derleme zamanı hatası oluşur.When a continue
statement occurs within a finally
block, the target of the continue
statement must be within the same finally
block; otherwise a compile-time error occurs.
Bir continue
ifade aşağıdaki gibi yürütülür:A continue
statement is executed as follows:
continue
İfade ilişkili bloklarla bir veya daha fazlatry
finally
bloktan çıkıldığında denetim başlangıçta enfinally
içteki deyimin bloğuna aktarılırtry
.If thecontinue
statement exits one or moretry
blocks with associatedfinally
blocks, control is initially transferred to thefinally
block of the innermosttry
statement. Ve denetimi bir bloğun bitiş noktasına ulaştığındafinally
, Denetimfinally
sonraki kapsayan deyimin bloğuna aktarılırtry
.When and if control reaches the end point of afinally
block, control is transferred to thefinally
block of the next enclosingtry
statement. Bu işlem,finally
tüm arayatry
eklenen deyimlerin blokları yürütülene kadar yinelenir.This process is repeated until thefinally
blocks of all interveningtry
statements have been executed.- Denetim, deyimin hedefine aktarılır
continue
.Control is transferred to the target of thecontinue
statement.
Bir continue
ifade denetimi başka bir yerde bir yere aktarmadığı için, bir deyimin bitiş noktasına continue
hiçbir şekilde ulaşılamıyor.Because a continue
statement unconditionally transfers control elsewhere, the end point of a continue
statement is never reachable.
Goto ekstresiThe goto statement
goto
İfade, denetimi bir etiketi tarafından işaretlenen bir ifadeye aktarır.The goto
statement transfers control to a statement that is marked by a label.
goto_statement
: 'goto' identifier ';'
| 'goto' 'case' constant_expression ';'
| 'goto' 'default' ';'
;
Bir goto
Identifier ifadesinin hedefi, verilen etikete sahip etiketli deyimdir.The target of a goto
identifier statement is the labeled statement with the given label. Verilen ada sahip bir etiket geçerli işlev üyesinde yoksa veya goto
ifade etiketin kapsamı içinde değilse, bir derleme zamanı hatası oluşur.If a label with the given name does not exist in the current function member, or if the goto
statement is not within the scope of the label, a compile-time error occurs. Bu kural, iç içe geçmiş bir kapsamın goto
denetimini dışarı aktarmak için bir deyimin kullanılmasına izin verir.This rule permits the use of a goto
statement to transfer control out of a nested scope, but not into a nested scope. ÖrnekteIn the example
using System;
class Test
{
static void Main(string[] args) {
string[,] table = {
{"Red", "Blue", "Green"},
{"Monday", "Wednesday", "Friday"}
};
foreach (string str in args) {
int row, colm;
for (row = 0; row <= 1; ++row)
for (colm = 0; colm <= 2; ++colm)
if (str == table[row,colm])
goto done;
Console.WriteLine("{0} not found", str);
continue;
done:
Console.WriteLine("Found {0} at [{1}][{2}]", str, row, colm);
}
}
}
bir goto
ifade, iç içe bir kapsamın denetimini aktarmak için kullanılır.a goto
statement is used to transfer control out of a nested scope.
Bir deyimin hedefi, goto case
switch
belirtilen sabit değere sahip bir etiketi içeren hemen kapsayan deyimindeki (Switch deyimindeki) ifade listesidir case
.The target of a goto case
statement is the statement list in the immediately enclosing switch
statement (The switch statement), which contains a case
label with the given constant value. goto case
Deyimle çevrelenemez switch
, constant_expression örtük olarak dönüştürülebilir (örtük dönüştürmeler), en yakın kapsayan deyimin yöneten türüne switch
veya en yakın kapsayan switch
ifadede case
verilen sabit değere sahip bir etiket içermiyorsa, derleme zamanı hatası oluşur.If the goto case
statement is not enclosed by a switch
statement, if the constant_expression is not implicitly convertible (Implicit conversions) to the governing type of the nearest enclosing switch
statement, or if the nearest enclosing switch
statement does not contain a case
label with the given constant value, a compile-time error occurs.
Bir deyimin hedefi, goto default
switch
bir etiketi içeren hemen kapsayan deyimindeki (Switch deyimindeki) ifade listesidir default
.The target of a goto default
statement is the statement list in the immediately enclosing switch
statement (The switch statement), which contains a default
label. goto default
İfade bir deyimle çevrede yoksa switch
veya en yakın kapsayan switch
ifade bir etiket içermiyorsa, default
derleme zamanı hatası oluşur.If the goto default
statement is not enclosed by a switch
statement, or if the nearest enclosing switch
statement does not contain a default
label, a compile-time error occurs.
Bir goto
ifade bir finally
bloğundan (TRY ifadesiyle) çıkabilir.A goto
statement cannot exit a finally
block (The try statement). Bir goto
blok içinde bir ifade gerçekleştiğinde finally
, goto
deyimin hedefi aynı blok içinde olmalıdır finally
, aksi takdirde bir derleme zamanı hatası oluşur.When a goto
statement occurs within a finally
block, the target of the goto
statement must be within the same finally
block, or otherwise a compile-time error occurs.
Bir goto
ifade aşağıdaki gibi yürütülür:A goto
statement is executed as follows:
goto
İfade ilişkili bloklarla bir veya daha fazlatry
finally
bloktan çıkıldığında denetim başlangıçta enfinally
içteki deyimin bloğuna aktarılırtry
.If thegoto
statement exits one or moretry
blocks with associatedfinally
blocks, control is initially transferred to thefinally
block of the innermosttry
statement. Ve denetimi bir bloğun bitiş noktasına ulaştığındafinally
, Denetimfinally
sonraki kapsayan deyimin bloğuna aktarılırtry
.When and if control reaches the end point of afinally
block, control is transferred to thefinally
block of the next enclosingtry
statement. Bu işlem,finally
tüm arayatry
eklenen deyimlerin blokları yürütülene kadar yinelenir.This process is repeated until thefinally
blocks of all interveningtry
statements have been executed.- Denetim, deyimin hedefine aktarılır
goto
.Control is transferred to the target of thegoto
statement.
Bir goto
ifade denetimi başka bir yerde bir yere aktarmadığı için, bir deyimin bitiş noktasına goto
hiçbir şekilde ulaşılamıyor.Because a goto
statement unconditionally transfers control elsewhere, the end point of a goto
statement is never reachable.
Return ekstresiThe return statement
return
İfadesi, denetimi deyimin göründüğü işlevin geçerli çağıranına döndürür return
.The return
statement returns control to the current caller of the function in which the return
statement appears.
return_statement
: 'return' expression? ';'
;
return
İfadesi olmayan bir deyim, yalnızca bir değeri hesaplamayan bir işlev üyesinde, yani, sonuç türü (Yöntem gövdesi), bir void
set
özelliğin veya dizin oluşturucunun erişimcisi, bir olay, bir add
remove
örnek Oluşturucu, statik oluşturucu veya yok edicisi olan bir işlev üyesinde kullanılabilir.A return
statement with no expression can be used only in a function member that does not compute a value, that is, a method with the result type (Method body) void
, the set
accessor of a property or indexer, the add
and remove
accessors of an event, an instance constructor, a static constructor, or a destructor.
return
İfadesi içeren bir deyim yalnızca bir değeri hesaplayan bir işlev üyesinde, diğer bir deyişle, void olmayan sonuç türü olan bir yöntem, get
bir özellik veya dizin oluşturucunun erişimcisi veya Kullanıcı tanımlı bir operatör ile kullanılabilir.A return
statement with an expression can only be used in a function member that computes a value, that is, a method with a non-void result type, the get
accessor of a property or indexer, or a user-defined operator. Örtük dönüştürme (örtük dönüştürmeler), ifadenin türünden kapsayan işlev üyesinin dönüş türüne sahip olmalıdır.An implicit conversion (Implicit conversions) must exist from the type of the expression to the return type of the containing function member.
Return deyimleri, anonim işlev ifadelerinin gövdesinde de kullanılabilir (anonim işlev ifadeleri) ve bu işlevler için hangi dönüştürmelerin var olduğunu belirlemeye katılabilirsiniz.Return statements can also be used in the body of anonymous function expressions (Anonymous function expressions), and participate in determining which conversions exist for those functions.
Bir return
deyimin finally
bloğunda (TRY ifadesinde) görünmesi için derleme zamanı hatası.It is a compile-time error for a return
statement to appear in a finally
block (The try statement).
Bir return
ifade aşağıdaki gibi yürütülür:A return
statement is executed as follows:
return
Deyim bir ifade belirtiyorsa, ifade değerlendirilir ve elde edilen değer, örtük bir dönüştürme tarafından içerilen işlevin dönüş türüne dönüştürülür.If thereturn
statement specifies an expression, the expression is evaluated and the resulting value is converted to the return type of the containing function by an implicit conversion. Dönüştürmenin sonucu, işlev tarafından üretilen sonuç değeri haline gelir.The result of the conversion becomes the result value produced by the function.return
Deyimle ilişkilendirilmiş blokları olan bir veya daha fazlatry
ya dacatch
blok varsafinally
, denetim başlangıçta enfinally
içteki deyimin bloğuna aktarılırtry
.If thereturn
statement is enclosed by one or moretry
orcatch
blocks with associatedfinally
blocks, control is initially transferred to thefinally
block of the innermosttry
statement. Ve denetimi bir bloğun bitiş noktasına ulaştığındafinally
, Denetimfinally
sonraki kapsayan deyimin bloğuna aktarılırtry
.When and if control reaches the end point of afinally
block, control is transferred to thefinally
block of the next enclosingtry
statement. Bu işlem,finally
kapsayan tümtry
deyimlerin blokları yürütülene kadar yinelenir.This process is repeated until thefinally
blocks of all enclosingtry
statements have been executed.- İçeren işlev bir zaman uyumsuz işlev değilse, denetim, içerilen işlevin çağıranına, varsa sonuç değeriyle birlikte döndürülür.If the containing function is not an async function, control is returned to the caller of the containing function along with the result value, if any.
- İçeren işlev bir zaman uyumsuz işlevtiyse, Denetim geçerli çağırana döndürülür ve sonuç değeri varsa, (Numaralandırıcı arabirimleri) bölümünde açıklandığı gibi Return görevinde kaydedilir.If the containing function is an async function, control is returned to the current caller, and the result value, if any, is recorded in the return task as described in (Enumerator interfaces).
Bir return
ifade denetimi başka bir yerde bir yere aktarmadığı için, bir deyimin bitiş noktasına return
hiçbir şekilde ulaşılamıyor.Because a return
statement unconditionally transfers control elsewhere, the end point of a return
statement is never reachable.
Throw deyimleriThe throw statement
throw
İfade bir özel durum oluşturur.The throw
statement throws an exception.
throw_statement
: 'throw' expression? ';'
;
throw
İfadesi içeren bir deyim, ifade hesaplanarak üretilen değeri oluşturur.A throw
statement with an expression throws the value produced by evaluating the expression. İfade, System.Exception
System.Exception
System.Exception
etkin taban sınıfı olarak (veya alt sınıfı) olan bir tür parametre türünden veya ondan türetilen bir sınıf türünün sınıf türünün bir değerini belirtmelidir.The expression must denote a value of the class type System.Exception
, of a class type that derives from System.Exception
or of a type parameter type that has System.Exception
(or a subclass thereof) as its effective base class. İfadenin değerlendirmesi oluşursa null
System.NullReferenceException
bunun yerine bir oluşturulur.If evaluation of the expression produces null
, a System.NullReferenceException
is thrown instead.
throw
İfadesi olmayan bir deyim yalnızca bir catch
blokta kullanılabilir, bu durumda deyim o blok tarafından işlenmekte olan özel durumu yeniden atar catch
.A throw
statement with no expression can be used only in a catch
block, in which case that statement re-throws the exception that is currently being handled by that catch
block.
Bir throw
ifade denetimi başka bir yerde bir yere aktarmadığı için, bir deyimin bitiş noktasına throw
hiçbir şekilde ulaşılamıyor.Because a throw
statement unconditionally transfers control elsewhere, the end point of a throw
statement is never reachable.
Bir özel durum oluştuğunda denetim, catch
özel durumu işleyebilen bir kapsayan ifadede ilk yan tümcesine aktarılır try
.When an exception is thrown, control is transferred to the first catch
clause in an enclosing try
statement that can handle the exception. Oluşturulan özel durumun noktasından, uygun özel durum işleyicisine denetim aktarma noktasına gerçekleşen işlem *özel durum yayma _ olarak bilinir.The process that takes place from the point of the exception being thrown to the point of transferring control to a suitable exception handler is known as *exception propagation _. Bir özel durumun yayılması, catch
özel durumla eşleşen bir yan tümce bulunana kadar aşağıdaki adımları tekrar tekrar değerlendirmeden oluşur.Propagation of an exception consists of repeatedly evaluating the following steps until a catch
clause that matches the exception is found. Bu açıklamada _ throw noktası* başlangıçta özel durumun oluşturulduğu konumdur.In this description, the _ throw point* is initially the location at which the exception is thrown.
Geçerli işlev üyesinde,
try
throw noktasını kapsayan her bir ifade incelenir.In the current function member, eachtry
statement that encloses the throw point is examined. Her bir bildirimdeS
, en içteki bildirimiyle başlayıp entry
dıştaki ifadesiyle sona ermek üzeretry
Aşağıdaki adımlar değerlendirilir:For each statementS
, starting with the innermosttry
statement and ending with the outermosttry
statement, the following steps are evaluated:try
BloğuS
bir veya daha fazla yan tümcesini içeriyorsa ve bu blok bir veya daha fazlacatch
yan tümce içeriyorsa,catch
yan tümce, TRY ifadesindebelirtilen kurallara göre özel durum için uygun bir işleyicinin yerini bulmak üzere görünüm sırasına göre incelenir.If thetry
block ofS
encloses the throw point and if S has one or morecatch
clauses, thecatch
clauses are examined in order of appearance to locate a suitable handler for the exception, according to the rules specified in Section The try statement. Eşleşen bircatch
yan tümce varsa, özel durum yayma, denetim bu yan tümce bloğuna aktarılarak tamamlanırcatch
.If a matchingcatch
clause is located, the exception propagation is completed by transferring control to the block of thatcatch
clause.Aksi takdirde,
try
blok veya bircatch
bloğuS
throw noktasını barındırır ve eğerS
bir blok içeriyorsafinally
Denetimfinally
bloğa aktarılır.Otherwise, if thetry
block or acatch
block ofS
encloses the throw point and ifS
has afinally
block, control is transferred to thefinally
block.finally
Blok başka bir özel durum oluşturursa, geçerli özel durumun işlenmesi sonlandırılır.If thefinally
block throws another exception, processing of the current exception is terminated. Aksi takdirde, denetim bloğun bitiş noktasına ulaştığındafinally
, geçerli özel durumun işlenmesi devam eder.Otherwise, when control reaches the end point of thefinally
block, processing of the current exception is continued.
Geçerli işlev çağrısında bir özel durum işleyicisi bulunmuyorsa, işlev çağırma sonlandırılır ve aşağıdakilerden biri oluşur:If an exception handler was not located in the current function invocation, the function invocation is terminated, and one of the following occurs:
Geçerli işlev zaman uyumsuz ise, yukarıdaki adımlar işlev üyesinin çağrıldığı ifadeye karşılık gelen bir throw noktasıyla işlevin çağıranı için yinelenir.If the current function is non-async, the steps above are repeated for the caller of the function with a throw point corresponding to the statement from which the function member was invoked.
Geçerli işlev zaman uyumsuz ve görev döndürüyor ise, özel durum, Numaralandırıcı arabirimlerindeaçıklandığı şekilde hatalı veya iptal edilmiş duruma yerleştirilen geri dönüş görevine kaydedilir.If the current function is async and task-returning, the exception is recorded in the return task, which is put into a faulted or cancelled state as described in Enumerator interfaces.
Geçerli işlev zaman uyumsuz ve void döndürüyorsa, geçerli iş parçacığının eşitleme bağlamı, sıralanabilir arabirimlerdeaçıklandığı gibi bilgilendirilir.If the current function is async and void-returning, the synchronization context of the current thread is notified as described in Enumerable interfaces.
Özel durum işleme geçerli iş parçacığında tüm işlev üyesi çağırmaları sonlandırdığında, iş parçacığının özel durum için bir işleyici olmadığını belirten bir iş parçacığının kendisi sonlandırılır.If the exception processing terminates all function member invocations in the current thread, indicating that the thread has no handler for the exception, then the thread is itself terminated. Bu sonlandırmanın etkisi, uygulama tanımlı ' dır.The impact of such termination is implementation-defined.
TRY deyimleriThe try statement
try
İfade, bir bloğun yürütülmesi sırasında oluşan özel durumları yakalamak için bir mekanizma sağlar.The try
statement provides a mechanism for catching exceptions that occur during execution of a block. Ayrıca,, try
denetimi deyimden çıktığında her zaman yürütülen bir kod bloğunu belirtme özelliği de sağlar try
.Furthermore, the try
statement provides the ability to specify a block of code that is always executed when control leaves the try
statement.
try_statement
: 'try' block catch_clause+
| 'try' block finally_clause
| 'try' block catch_clause+ finally_clause
;
catch_clause
: 'catch' exception_specifier? exception_filter? block
;
exception_specifier
: '(' type identifier? ')'
;
exception_filter
: 'when' '(' expression ')'
;
finally_clause
: 'finally' block
;
Üç olası deyim biçimi vardır try
:There are three possible forms of try
statements:
- Bir
try
blok ve ardından bir veya daha fazlacatch
blok gelir.Atry
block followed by one or morecatch
blocks. - Bir blok
try
ve ardından bir blok gelirfinally
.Atry
block followed by afinally
block. - Bir blok ve ardından bir blok tarafından izlenen bir
try
veya daha fazla blokcatch
finally
.Atry
block followed by one or morecatch
blocks followed by afinally
block.
Bir catch
yan tümce bir exception_specifier belirttiğinde, türü System.Exception
, System.Exception
System.Exception
geçerli temel sınıfı olarak (veya bir alt sınıf) içeren tür parametre türünden veya türetilen bir tür olmalıdır.When a catch
clause specifies an exception_specifier, the type must be System.Exception
, a type that derives from System.Exception
or a type parameter type that has System.Exception
(or a subclass thereof) as its effective base class.
Bir catch
yan tümce her ikisi de tanımlayıcı içeren bir exception_specifier belirttiğinde, belirtilen ada ve türe ilişkin bir *özel durum değişkeni tanımlanmış olur.When a catch
clause specifies both an exception_specifier with an identifier, an *exception variable _ of the given name and type is declared. Özel durum değişkeni, yan tümcesini genişleten bir kapsama sahip yerel bir değişkene karşılık gelir catch
.The exception variable corresponds to a local variable with a scope that extends over the catch
clause. _Exception_filter * ve bloğunun yürütülmesi sırasında, özel durum değişkeni işlenmekte olan özel durumu temsil eder.During execution of the _exception_filter* and block, the exception variable represents the exception currently being handled. Kesin atama denetimi amacıyla, özel durum değişkeni tüm kapsamda kesin olarak atanır olarak değerlendirilir.For purposes of definite assignment checking, the exception variable is considered definitely assigned in its entire scope.
Bir catch
yan tümce bir özel durum değişkeni adı içermiyorsa, filtre ve bloktaki özel durum nesnesine erişmek olanaksız olur catch
.Unless a catch
clause includes an exception variable name, it is impossible to access the exception object in the filter and catch
block.
Bir catch
exception_specifier belirtmeyen bir yan tümce genel catch
yan tümce olarak adlandırılır.A catch
clause that does not specify an exception_specifier is called a general catch
clause.
Bazı programlama dilleri, ' den türetilmiş bir nesne olarak gösterilemeyen özel durumları destekleyebilir System.Exception
, ancak bu tür özel durumlar hiçbir şekilde C# kodu tarafından üretilmeyebilir.Some programming languages may support exceptions that are not representable as an object derived from System.Exception
, although such exceptions could never be generated by C# code. catch
Bu tür özel durumları yakalamak için genel bir yan tümce kullanılabilir.A general catch
clause may be used to catch such exceptions. Bu nedenle, genel bir catch
yan tümce türü belirten bir değer olan anlam, System.Exception
diğer bir deyişle diğer dillerdeki özel durumları da yakalayabiliriz.Thus, a general catch
clause is semantically different from one that specifies the type System.Exception
, in that the former may also catch exceptions from other languages.
Bir özel durum için işleyicinin yerini bulmak için, catch
yan tümceler sözlü sırada incelenir.In order to locate a handler for an exception, catch
clauses are examined in lexical order. Bir catch
yan tümce bir tür belirtiyorsa, ancak özel durum filtresi yoksa, catch
try
Bu tür ile aynı veya ondan türetilmiş bir türü belirtmek için aynı deyimdeki sonraki yan tümce için derleme zamanı hatası olur.If a catch
clause specifies a type but no exception filter, it is a compile-time error for a later catch
clause in the same try
statement to specify a type that is the same as, or is derived from, that type. Bir catch
yan tümce hiçbir tür ve filtre yoksa, catch
Bu deyimin son yan tümcesi olmalıdır try
.If a catch
clause specifies no type and no filter, it must be the last catch
clause for that try
statement.
Bir catch
blok içinde, throw
ifadesi olmayan bir deyim (throw deyimi), blok tarafından yakalanan özel durumu yeniden oluşturmak için kullanılabilir catch
.Within a catch
block, a throw
statement (The throw statement) with no expression can be used to re-throw the exception that was caught by the catch
block. Bir özel durum değişkenine atamalar yeniden oluşturulan özel durumu değiştirmez.Assignments to an exception variable do not alter the exception that is re-thrown.
ÖrnekteIn the example
using System;
class Test
{
static void F() {
try {
G();
}
catch (Exception e) {
Console.WriteLine("Exception in F: " + e.Message);
e = new Exception("F");
throw; // re-throw
}
}
static void G() {
throw new Exception("G");
}
static void Main() {
try {
F();
}
catch (Exception e) {
Console.WriteLine("Exception in Main: " + e.Message);
}
}
}
yöntemi F
bir özel durumu yakalar, konsola bazı tanılama bilgileri yazar, özel durum değişkenini değiştirir ve özel durumu yeniden oluşturur.the method F
catches an exception, writes some diagnostic information to the console, alters the exception variable, and re-throws the exception. Yeniden oluşturulan özel durum özgün özel durumdur, bu nedenle oluşturulan çıkış şu şekilde yapılır:The exception that is re-thrown is the original exception, so the output produced is:
Exception in F: G
Exception in Main: G
İlk catch bloğu e
geçerli özel durumu yeniden oluşturmak yerine oluşursa, üretilen çıkış aşağıdaki gibi olacaktır:If the first catch block had thrown e
instead of rethrowing the current exception, the output produced would be as follows:
Exception in F: G
Exception in Main: F
Bir break
continue
goto
blok dışına denetim aktarmak için, veya bildiriminde derleme zamanı hatasıdır finally
.It is a compile-time error for a break
, continue
, or goto
statement to transfer control out of a finally
block. break
continue
goto
Bir blok içinde bir, veya ifade oluştuğunda finally
, deyimin hedefi aynı blok içinde olmalıdır finally
, aksi takdirde bir derleme zamanı hatası oluşur.When a break
, continue
, or goto
statement occurs in a finally
block, the target of the statement must be within the same finally
block, or otherwise a compile-time error occurs.
Bir return
deyimin bir blokta oluşması için derleme zamanı hatası finally
.It is a compile-time error for a return
statement to occur in a finally
block.
Bir try
ifade aşağıdaki gibi yürütülür:A try
statement is executed as follows:
Denetim,
try
bloğa aktarılır.Control is transferred to thetry
block.Denetim, bloğunun bitiş noktasına ulaştığında
try
:When and if control reaches the end point of thetry
block:try
Deyimde bir blok varsafinally
,finally
blok yürütülür.If thetry
statement has afinally
block, thefinally
block is executed.- Denetim, deyimin bitiş noktasına aktarılır
try
.Control is transferred to the end point of thetry
statement.
try
Bloğun yürütülmesi sırasında ifadeye bir özel durum yayıldığındatry
:If an exception is propagated to thetry
statement during execution of thetry
block:catch
Yan tümceleri, varsa, özel durum için uygun bir işleyicinin yerini bulmak üzere görünüm sırasına göre incelenir.Thecatch
clauses, if any, are examined in order of appearance to locate a suitable handler for the exception. Bircatch
yan tümce bir tür belirtmezse veya özel durum türünü ya da özel durum türünün temel türünü belirtir:If acatch
clause does not specify a type, or specifies the exception type or a base type of the exception type:catch
Yan tümce bir özel durum değişkeni bildiriyorsa, özel durum nesnesi özel durum değişkenine atanır.If thecatch
clause declares an exception variable, the exception object is assigned to the exception variable.catch
Yan tümce bir özel durum filtresi bildirirse, filtre değerlendirilir.If thecatch
clause declares an exception filter, the filter is evaluated. Olarak değerlendirilirsefalse
, catch yan tümcesi bir eşleşme değildir ve aramacatch
uygun bir işleyici için sonraki yan tümcelerde devam eder.If it evaluates tofalse
, the catch clause is not a match, and the search continues through any subsequentcatch
clauses for a suitable handler.- Aksi takdirde,
catch
yan tümce eşleşme olarak değerlendirilir ve denetim eşleşencatch
bloğa aktarılır.Otherwise, thecatch
clause is considered a match, and control is transferred to the matchingcatch
block. - Denetim, bloğunun bitiş noktasına ulaştığında
catch
:When and if control reaches the end point of thecatch
block:try
Deyimde bir blok varsafinally
,finally
blok yürütülür.If thetry
statement has afinally
block, thefinally
block is executed.- Denetim, deyimin bitiş noktasına aktarılır
try
.Control is transferred to the end point of thetry
statement.
try
Bloğun yürütülmesi sırasında ifadeye bir özel durum yayıldığındacatch
:If an exception is propagated to thetry
statement during execution of thecatch
block:try
Deyimde bir blok varsafinally
,finally
blok yürütülür.If thetry
statement has afinally
block, thefinally
block is executed.- Özel durum bir sonraki kapsayan
try
ifadeye yayılır.The exception is propagated to the next enclosingtry
statement.
try
Deyimin hiçbircatch
yan tümcesi yoksa veya hiçbircatch
yan tümce özel durumla eşleşmez:If thetry
statement has nocatch
clauses or if nocatch
clause matches the exception:try
Deyimde bir blok varsafinally
,finally
blok yürütülür.If thetry
statement has afinally
block, thefinally
block is executed.- Özel durum bir sonraki kapsayan
try
ifadeye yayılır.The exception is propagated to the next enclosingtry
statement.
Bir finally
bloğun deyimleri her zaman denetim bir ifadeden ayrıldığında yürütülür try
.The statements of a finally
block are always executed when control leaves a try
statement. Bu, denetim aktarımının normal yürütmenin sonucu olarak,,, break
continue
veya ifadesinin yürütülmesi ya da bir goto
return
özel durumun bir özel durum yaymasından kaynaklanan bir sonuç olarak oluşup oluşmadığını belirtir try
.This is true whether the control transfer occurs as a result of normal execution, as a result of executing a break
, continue
, goto
, or return
statement, or as a result of propagating an exception out of the try
statement.
Bir bloğun yürütülmesi sırasında bir özel durum oluşturulursa finally
ve aynı finally bloğu içinde yakalanmadığında, özel durum sonraki kapsayan try
ifadeye yayılır.If an exception is thrown during execution of a finally
block, and is not caught within the same finally block, the exception is propagated to the next enclosing try
statement. Yayılmakta olan işlemde başka bir özel durum varsa, bu özel durum kaybedilir.If another exception was in the process of being propagated, that exception is lost. Bir özel durumu yayma işlemi, throw
deyimin açıklamasında (throw deyimidir) daha ayrıntılı bir şekilde ele alınmıştır.The process of propagating an exception is discussed further in the description of the throw
statement (The throw statement).
try
try
Deyimin erişilebilir olması durumunda bir deyimin bloğuna erişilebilir try
.The try
block of a try
statement is reachable if the try
statement is reachable.
catch
try
Deyimde erişilebilir olduğunda bir deyimin bloğu erişilebilir olur try
.A catch
block of a try
statement is reachable if the try
statement is reachable.
finally
try
Deyimin erişilebilir olması durumunda bir deyimin bloğuna erişilebilir try
.The finally
block of a try
statement is reachable if the try
statement is reachable.
try
Aşağıdakilerin her ikisi de doğruysa, bir deyimin bitiş noktasına ulaşılabilir:The end point of a try
statement is reachable if both of the following are true:
- Bloğun bitiş noktasına
try
ulaşılabilir veya en az bir bloğun bitiş noktasıcatch
erişilebilir.The end point of thetry
block is reachable or the end point of at least onecatch
block is reachable. - Bir
finally
blok varsa, bloğun bitiş noktasınafinally
ulaşılabilir.If afinally
block is present, the end point of thefinally
block is reachable.
Checked ve unchecked deyimleriThe checked and unchecked statements
checked
Ve unchecked
deyimleri, tamsayı türü aritmetik işlemler ve dönüştürmeler için taşma denetimi bağlamını denetlemek için kullanılır.The checked
and unchecked
statements are used to control the overflow checking context for integral-type arithmetic operations and conversions.
checked_statement
: 'checked' block
;
unchecked_statement
: 'unchecked' block
;
checked
Deyimi, bloktaki tüm ifadelerin işaretlenmiş bir bağlamda değerlendirilmesini sağlar ve unchecked
deyim, bloktaki tüm ifadelerin işaretlenmemiş bir bağlamda değerlendirilmesini sağlar.The checked
statement causes all expressions in the block to be evaluated in a checked context, and the unchecked
statement causes all expressions in the block to be evaluated in an unchecked context.
checked
Ve unchecked
deyimleri, checked
ve unchecked
işleçleri (Checked ve unchecked işleçleri), ifadeler yerine bloklar üzerinde çalıştıkları durumlar hariç, ve işleçlerine tam olarak eşdeğerdir.The checked
and unchecked
statements are precisely equivalent to the checked
and unchecked
operators (The checked and unchecked operators), except that they operate on blocks instead of expressions.
Lock deyimleriThe lock statement
lock
İfade, belirli bir nesne için karşılıklı dışlama kilidini edinir, bir ifade yürütür ve sonra kilidi serbest bırakır.The lock
statement obtains the mutual-exclusion lock for a given object, executes a statement, and then releases the lock.
lock_statement
: 'lock' '(' expression ')' embedded_statement
;
Bir lock
deyimin ifadesi reference_type olarak bilinen bir türün değerini belirtmelidir.The expression of a lock
statement must denote a value of a type known to be a reference_type. Bir deyimin ifadesi için hiçbir örtük paketleme dönüştürmesi (kutulamadönüştürmesi) yapılmaz lock
ve bu nedenle, ifadenin bir value_type değerini belirtmek için derleme zamanı hatası vardır.No implicit boxing conversion (Boxing conversions) is ever performed for the expression of a lock
statement, and thus it is a compile-time error for the expression to denote a value of a value_type.
lock
Formun bir açıklamasıA lock
statement of the form
lock (x) ...
x
reference_type bir ifadesi ise, tam olarak şu şekilde eşdeğerdirwhere x
is an expression of a reference_type, is precisely equivalent to
bool __lockWasTaken = false;
try {
System.Threading.Monitor.Enter(x, ref __lockWasTaken);
...
}
finally {
if (__lockWasTaken) System.Threading.Monitor.Exit(x);
}
hariç x
yalnızca bir kez değerlendirilir.except that x
is only evaluated once.
Karşılıklı dışlama kilidi tutulurken, aynı yürütme iş parçacığında yürütülen kod da kilidi alabilir ve serbest bırakabilir.While a mutual-exclusion lock is held, code executing in the same execution thread can also obtain and release the lock. Ancak, diğer iş parçacıklarında yürütülen kodun kilit serbest bırakılana kadar kilidi almasını engellenir.However, code executing in other threads is blocked from obtaining the lock until the lock is released.
System.Type
Statik verilere erişimin eşitlenmesi için nesneleri kilitleme önerilmez.Locking System.Type
objects in order to synchronize access to static data is not recommended. Diğer kod aynı tür üzerinde kilitlenebilir, bu da kilitlenmeye neden olabilir.Other code might lock on the same type, which can result in deadlock. Özel bir statik nesneyi kilitleyerek statik verilere erişimi eşitlememeye daha iyi bir yaklaşım.A better approach is to synchronize access to static data by locking a private static object. Örnek:For example:
class Cache
{
private static readonly object synchronizationObject = new object();
public static void Add(object x) {
lock (Cache.synchronizationObject) {
...
}
}
public static void Remove(object x) {
lock (Cache.synchronizationObject) {
...
}
}
}
Using deyimiThe using statement
using
İfade bir veya daha fazla kaynak edinir, bir ifade yürütür ve sonra kaynağı atar.The using
statement obtains one or more resources, executes a statement, and then disposes of the resource.
using_statement
: 'using' '(' resource_acquisition ')' embedded_statement
;
resource_acquisition
: local_variable_declaration
| expression
;
Kaynak System.IDisposable
, adlı tek bir parametresiz yöntemi içeren, uygulayan bir sınıf veya yapı olur Dispose
.A resource is a class or struct that implements System.IDisposable
, which includes a single parameterless method named Dispose
. Kaynak kullanan kod, Dispose
kaynağın artık gerekli olmadığını belirtmek için çağrı yapabilir.Code that is using a resource can call Dispose
to indicate that the resource is no longer needed. Dispose
Çağrılırsa, çöp toplamanın bir sonucu olarak otomatik çıkarma işlemi gerçekleşir.If Dispose
is not called, then automatic disposal eventually occurs as a consequence of garbage collection.
Resource_acquisition biçimi local_variable_declaration , local_variable_declaration türü dynamic
ya da örtük olarak dönüştürülebilir bir tür olmalıdır System.IDisposable
.If the form of resource_acquisition is local_variable_declaration then the type of the local_variable_declaration must be either dynamic
or a type that can be implicitly converted to System.IDisposable
. Resource_acquisition biçimi ifade ise, bu ifadenin öğesine örtülü olarak dönüştürülebilir olması gerekir System.IDisposable
.If the form of resource_acquisition is expression then this expression must be implicitly convertible to System.IDisposable
.
Resource_acquisition belirtilen yerel değişkenler salt okunurdur ve bir başlatıcı içermelidir.Local variables declared in a resource_acquisition are read-only, and must include an initializer. Katıştırılmış ifade bu yerel değişkenleri değiştirmeye çalışırsa (atama veya ve işleçler aracılığıyla) bir derleme zamanı hatası oluşur ++
--
, bunların adresini alın veya ref
ya da parametreleri veya parametreleri olarak geçirin out
.A compile-time error occurs if the embedded statement attempts to modify these local variables (via assignment or the ++
and --
operators) , take the address of them, or pass them as ref
or out
parameters.
Bir using
ifade üç parçaya çevrilir: alma, kullanım ve çıkarma.A using
statement is translated into three parts: acquisition, usage, and disposal. Kaynağın kullanımı dolaylı olarak try
bir yan tümce içeren bir ifadeye alınmıştır finally
.Usage of the resource is implicitly enclosed in a try
statement that includes a finally
clause. Bu finally
yan tümce kaynağı ortadan kaldırır.This finally
clause disposes of the resource. Bir null
kaynak elde alınırsa, hiçbir çağrı Dispose
yapılmaz ve hiçbir özel durum oluşturulmaz.If a null
resource is acquired, then no call to Dispose
is made, and no exception is thrown. Kaynak türtür ise, dynamic
dönüştürmenin kullanımdan ve aktiften çıkarılmadan önce başarılı olmasını sağlamak için alma sırasında dinamik bir dinamik dönüştürme (örtük dinamik dönüştürmeler) üzerinden dinamik olarak dönüştürülür IDisposable
.If the resource is of type dynamic
it is dynamically converted through an implicit dynamic conversion (Implicit dynamic conversions) to IDisposable
during acquisition in order to ensure that the conversion is successful before the usage and disposal.
using
Formun bir açıklamasıA using
statement of the form
using (ResourceType resource = expression) statement
olası üç Genişlemeden birine karşılık gelir.corresponds to one of three possible expansions. ResourceType
Null yapılamayan bir değer türü olduğunda, genişletmeWhen ResourceType
is a non-nullable value type, the expansion is
{
ResourceType resource = expression;
try {
statement;
}
finally {
((IDisposable)resource).Dispose();
}
}
Aksi halde, ResourceType
null yapılabilir bir değer türü veya dışında bir başvuru türü olduğunda dynamic
, genişletmeOtherwise, when ResourceType
is a nullable value type or a reference type other than dynamic
, the expansion is
{
ResourceType resource = expression;
try {
statement;
}
finally {
if (resource != null) ((IDisposable)resource).Dispose();
}
}
Aksi halde, ne zaman, ResourceType
dynamic
genişletmeOtherwise, when ResourceType
is dynamic
, the expansion is
{
ResourceType resource = expression;
IDisposable d = (IDisposable)resource;
try {
statement;
}
finally {
if (d != null) d.Dispose();
}
}
Her iki genişlede de resource
değişken gömülü ifadede salt okunurdur ve d
değişkenine, gömülü ifadeye ve görünmez.In either expansion, the resource
variable is read-only in the embedded statement, and the d
variable is inaccessible in, and invisible to, the embedded statement.
Davranışın yukarıdaki genişlemeyle tutarlı olduğu sürece, bir uygulamanın belirli bir using ifadesini farklı bir şekilde uygulaması için, örneğin performans nedenleriyle, bir uygulamaya izin verilir.An implementation is permitted to implement a given using-statement differently, e.g. for performance reasons, as long as the behavior is consistent with the above expansion.
using
Formun bir açıklamasıA using
statement of the form
using (expression) statement
, mümkün olan üç genişleme sahiptir.has the same three possible expansions. Bu durumda, ResourceType
varsa, öğesinin derleme zamanı türü örtülü olarak oluşturulur expression
.In this case ResourceType
is implicitly the compile-time type of the expression
, if it has one. Aksi takdirde IDisposable
, arabirimin kendisi olarak kullanılır ResourceType
.Otherwise the interface IDisposable
itself is used as the ResourceType
. resource
Değişkenine, gömülü ifadeye, ve görünmez olarak erişilemez.The resource
variable is inaccessible in, and invisible to, the embedded statement.
Bir resource_acquisition local_variable_declaration formu aldığında, belirli bir türün birden çok kaynağını elde etmek mümkündür.When a resource_acquisition takes the form of a local_variable_declaration, it is possible to acquire multiple resources of a given type. using
Formun bir açıklamasıA using
statement of the form
using (ResourceType r1 = e1, r2 = e2, ..., rN = eN) statement
, iç içe geçmiş deyimlerin dizisine tam olarak eşdeğerdir using
:is precisely equivalent to a sequence of nested using
statements:
using (ResourceType r1 = e1)
using (ResourceType r2 = e2)
...
using (ResourceType rN = eN)
statement
Aşağıdaki örnek adlı bir dosya oluşturur log.txt
ve dosyaya iki satırlık metin yazar.The example below creates a file named log.txt
and writes two lines of text to the file. Örnek daha sonra bu dosyayı okumak için aynı dosyayı açar ve içerilen metin satırlarını konsola kopyalar.The example then opens that same file for reading and copies the contained lines of text to the console.
using System;
using System.IO;
class Test
{
static void Main() {
using (TextWriter w = File.CreateText("log.txt")) {
w.WriteLine("This is line one");
w.WriteLine("This is line two");
}
using (TextReader r = File.OpenText("log.txt")) {
string s;
while ((s = r.ReadLine()) != null) {
Console.WriteLine(s);
}
}
}
}
TextWriter
Ve TextReader
sınıfları IDisposable
arabirimini kullandığından, örnek, using
temel alınan dosyanın yazma veya okuma işlemlerinden sonra düzgün şekilde kapatılmasını sağlamak için deyimlerini kullanabilir.Since the TextWriter
and TextReader
classes implement the IDisposable
interface, the example can use using
statements to ensure that the underlying file is properly closed following the write or read operations.
Yield ekstresiThe yield statement
İfade, bir yineleyici yield
bloğunda (bloklar), bir yineleyicinin Numaralandırıcı nesnesine (Numaralandırıcı nesneleri) veya sıralanabilir nesne (numaralandırılabilir nesneler) bir değer vermek veya yinelemenin sonuna işaret etmek için kullanılır.The yield
statement is used in an iterator block (Blocks) to yield a value to the enumerator object (Enumerator objects) or enumerable object (Enumerable objects) of an iterator or to signal the end of the iteration.
yield_statement
: 'yield' 'return' expression ';'
| 'yield' 'break' ';'
;
yield
ayrılmış bir sözcük değil; yalnızca bir return
veya anahtar sözcüğünden hemen önce kullanıldığında özel anlamı vardır break
.yield
is not a reserved word; it has special meaning only when used immediately before a return
or break
keyword. Diğer bağlamlarda yield
tanımlayıcı olarak kullanılabilir.In other contexts, yield
can be used as an identifier.
yield
Aşağıda açıklandığı gibi bir deyimin görünebileceği çeşitli kısıtlamalar vardır.There are several restrictions on where a yield
statement can appear, as described in the following.
- Bir
yield
deyimin (herhangi bir biçimde) method_body, operator_body veya accessor_body dışında görünmesi için derleme zamanı hatası.It is a compile-time error for ayield
statement (of either form) to appear outside a method_body, operator_body or accessor_body - Bir
yield
deyimin (herhangi bir biçimde) anonim bir işlev içinde görünmesi için derleme zamanı hatasıdır.It is a compile-time error for ayield
statement (of either form) to appear inside an anonymous function. - Bir deyimin
yield
yan tümcesinde görünmesi için (her bir biçimde) bir derleme zamanı hatasıdırfinally
try
.It is a compile-time error for ayield
statement (of either form) to appear in thefinally
clause of atry
statement. - Bir
yield return
deyimin,try
herhangi bir yan tümce içeren bir ifadede görünmesini sağlayan derleme zamanı hatasıcatch
.It is a compile-time error for ayield return
statement to appear anywhere in atry
statement that contains anycatch
clauses.
Aşağıdaki örnekte, bazı geçerli ve geçersiz deyim kullanımları gösterilmektedir yield
.The following example shows some valid and invalid uses of yield
statements.
delegate IEnumerable<int> D();
IEnumerator<int> GetEnumerator() {
try {
yield return 1; // Ok
yield break; // Ok
}
finally {
yield return 2; // Error, yield in finally
yield break; // Error, yield in finally
}
try {
yield return 3; // Error, yield return in try...catch
yield break; // Ok
}
catch {
yield return 4; // Error, yield return in try...catch
yield break; // Ok
}
D d = delegate {
yield return 5; // Error, yield in an anonymous function
};
}
int MyMethod() {
yield return 1; // Error, wrong return type for an iterator block
}
Bir örtük dönüştürme (örtük dönüştürmeler), deyimdeki ifade türünün, yield return
yineleyicinin yield türüne (yield türü) sahip olması gerekir.An implicit conversion (Implicit conversions) must exist from the type of the expression in the yield return
statement to the yield type (Yield type) of the iterator.
Bir yield return
ifade aşağıdaki gibi yürütülür:A yield return
statement is executed as follows:
- Deyimde verilen ifade değerlendirilir, örtülü olarak yield türüne dönüştürülür ve
Current
Numaralandırıcı nesnesinin özelliğine atanır.The expression given in the statement is evaluated, implicitly converted to the yield type, and assigned to theCurrent
property of the enumerator object. - Yineleyici bloğunun yürütülmesi askıya alındı.Execution of the iterator block is suspended.
yield return
İfade bir veya daha fazlatry
blok içindeyse, ilişkilifinally
bloklar Şu anda yürütülmez.If theyield return
statement is within one or moretry
blocks, the associatedfinally
blocks are not executed at this time. MoveNext
Numaralandırıcı nesnesinin yöntemi,true
Numaralandırıcı nesnesinin bir sonraki öğeye başarıyla ilerlemediğini belirten, çağırana döner.TheMoveNext
method of the enumerator object returnstrue
to its caller, indicating that the enumerator object successfully advanced to the next item.
Numaralandırıcı nesnesinin yönteminin sonraki çağrısı, MoveNext
Yineleyici bloğunun son askıya alındığı yerden yürütülmesini sürdürür.The next call to the enumerator object's MoveNext
method resumes execution of the iterator block from where it was last suspended.
Bir yield break
ifade aşağıdaki gibi yürütülür:A yield break
statement is executed as follows:
yield break
Deyimle ilişkili blokları olan bir veya daha fazlatry
blok varsafinally
, denetim başlangıçta enfinally
içteki deyimin bloğuna aktarılırtry
.If theyield break
statement is enclosed by one or moretry
blocks with associatedfinally
blocks, control is initially transferred to thefinally
block of the innermosttry
statement. Ve denetimi bir bloğun bitiş noktasına ulaştığındafinally
, Denetimfinally
sonraki kapsayan deyimin bloğuna aktarılırtry
.When and if control reaches the end point of afinally
block, control is transferred to thefinally
block of the next enclosingtry
statement. Bu işlem,finally
kapsayan tümtry
deyimlerin blokları yürütülene kadar yinelenir.This process is repeated until thefinally
blocks of all enclosingtry
statements have been executed.- Denetim, yineleyici bloğunun çağıranına döndürülür.Control is returned to the caller of the iterator block. Bu,
MoveNext
Numaralandırıcı nesnesinin yöntemi ya daDispose
yöntemidir.This is either theMoveNext
method orDispose
method of the enumerator object.
Bir yield break
ifade denetimi başka bir yerde bir yere aktarmadığı için, bir deyimin bitiş noktasına yield break
hiçbir şekilde ulaşılamıyor.Because a yield break
statement unconditionally transfers control elsewhere, the end point of a yield break
statement is never reachable.