Null yapılabilir başvuru türleri belirtimiNullable Reference Types Specification
Bu, devam eden bir çalışmadır. birkaç bölüm eksik veya eksik.This is a work in progress - several parts are missing or incomplete.
Bu özellik, mevcut null yapılabilir değer türlerine iki yeni tür atanabilir tür (null yapılabilir başvuru türleri ve null atanabilir genel türler) ekler ve null güvenlik amacıyla statik bir akış analizi sunar.This feature adds two new kinds of nullable types (nullable reference types and nullable generic types) to the existing nullable value types, and introduces a static flow analysis for purpose of null-safety.
SyntaxSyntax
Null yapılabilir başvuru türleri ve null yapılabilir tür parametreleriNullable reference types and nullable type parameters
Null yapılabilir başvuru türleri ve null yapılabilir tür parametreleri, T? null yapılabilir değer türlerinin kısa biçimiyle aynı sözdizimine sahiptir, ancak karşılık gelen uzun bir biçime sahip değildir.Nullable reference types and nullable type parameters have the same syntax T? as the short form of nullable value types, but do not have a corresponding long form.
Belirtim amaçları doğrultusunda, geçerli nullable_type üretim olarak yeniden adlandırılır ve nullable_value_type nullable_reference_type nullable_type_parameter üretimler eklenir:For the purposes of the specification, the current nullable_type production is renamed to nullable_value_type, and nullable_reference_type and nullable_type_parameter productions are added:
type
: value_type
| reference_type
| nullable_type_parameter
| type_parameter
| type_unsafe
;
reference_type
: ...
| nullable_reference_type
;
nullable_reference_type
: non_nullable_reference_type '?'
;
non_nullable_reference_type
: reference_type
;
nullable_type_parameter
: non_nullable_non_value_type_parameter '?'
;
non_nullable_non_value_type_parameter
: type_parameter
;
non_nullable_reference_typeİçindeki içinde nullable_reference_type null yapılamayan bir başvuru türü (sınıf, arabirim, temsilci veya dizi) olması gerekir.The non_nullable_reference_type in a nullable_reference_type must be a nonnullable reference type (class, interface, delegate or array).
non_nullable_non_value_type_parameterİçinde, nullable_type_parameter bir değer türü olarak kısıtlanmış olmayan bir tür parametresi olmalıdır.The non_nullable_non_value_type_parameter in nullable_type_parameter must be a type parameter that isn't constrained to be a value type.
Null yapılabilir başvuru türleri ve null yapılabilir tür parametreleri aşağıdaki konumlarda gerçekleşemez:Nullable reference types and nullable type parameters cannot occur in the following positions:
- temel sınıf veya arabirim olarakas a base class or interface
- alıcı olarak
member_accessas the receiver of amember_access - içindeki olarak
type``object_creation_expressionas thetypein anobject_creation_expression - içindeki olarak
delegate_type``delegate_creation_expressionas thedelegate_typein adelegate_creation_expression typeis_expression' a, acatch_clauseveya atype_patternas thetypein anis_expression, acatch_clauseor atype_patterninterfacetam nitelikli arabirim üye adındaas theinterfacein a fully qualified interface member name
Bir uyarı, nullable_reference_type ve nullable_type_parameter devre dışı bırakılmış bir null değer ek açıklaması bağlamında verilir.A warning is given on a nullable_reference_type and nullable_type_parameter in a disabled nullable annotation context.
class ve class? kısıtlamaclass and class? constraint
classKısıtlama null yapılabilir bir karşılığına sahiptir class? :The class constraint has a nullable counterpart class?:
primary_constraint
: ...
| 'class' '?'
;
class( Etkin bir ek açıklama bağlamında) ile kısıtlanmış bir tür parametresi, null olamayan bir başvuru türüyle oluşturulmalıdır.A type parameter constrained with class (in an enabled annotation context) must be instantiated with a nonnullable reference type.
class?(Veya class devre dışı bir ek açıklama bağlamında) kısıtlanmış bir tür parametresi, null yapılabilir veya null yapılamayan bir başvuru türü ile oluşturulabilir.A type parameter constrained with class? (or class in a disabled annotation context) may either be instantiated with a nullable or nonnullable reference type.
class? Devre dışı bir ek açıklama bağlamındaki kısıtlamada bir uyarı verilir.A warning is given on a class? constraint in a disabled annotation context.
notnull kısıtlamasınotnull constraint
İle kısıtlanmış bir tür parametresi notnull null yapılabilir bir tür olamaz (null yapılabilir değer türü, Nullable başvuru türü veya null yapılabilir tür parametresi).A type parameter constrained with notnull may not be a nullable type (nullable value type, nullable reference type or nullable type parameter).
primary_constraint
: ...
| 'notnull'
;
default kısıtlamasıdefault constraint
Kısıtlama, "Nullable default T? değer türü" () öğesinden "Nullable tür parametresi" anlamını ortadan kaldırmak için bir yöntem geçersiz kılma veya açık uygulama üzerinde kullanılabilir Nullable<T> .The default constraint can be used on a method override or explicit implementation to disambiguate T? meaning "nullable type parameter" from "nullable value type" (Nullable<T>). Kısıtlama yok, default T? geçersiz kılma veya açık uygulamadaki bir sözdizimi şu şekilde yorumlanır Nullable<T>Lacking the default constraint a T? syntax in an override or explicit implementation will be interpreted as Nullable<T>
Bkz. https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/unconstrained-type-parameter-annotations.md#default-constraintSee https://github.com/dotnet/csharplang/blob/master/proposals/csharp-9.0/unconstrained-type-parameter-annotations.md#default-constraint
Null-forverme işleciThe null-forgiving operator
Onarma sonrası ! işlecine null-forverme işleci denir.The post-fix ! operator is called the null-forgiving operator. Bu, bir primary_expression veya null_conditional_expression içinde uygulanabilir:It can be applied on a primary_expression or within a null_conditional_expression:
primary_expression
: ...
| null_forgiving_expression
;
null_forgiving_expression
: primary_expression '!'
;
null_conditional_expression
: primary_expression null_conditional_operations_no_suppression suppression?
;
null_conditional_operations_no_suppression
: null_conditional_operations? '?' '.' identifier type_argument_list?
| null_conditional_operations? '?' '[' argument_list ']'
| null_conditional_operations '.' identifier type_argument_list?
| null_conditional_operations '[' argument_list ']'
| null_conditional_operations '(' argument_list? ')'
;
null_conditional_operations
: null_conditional_operations_no_suppression suppression?
;
suppression
: '!'
;
Örnek:For example:
var v = expr!;
expr!.M();
_ = a?.b!.c;
primary_expressionVe, null_conditional_operations_no_suppression null yapılabilir bir türde olmalıdır.The primary_expression and null_conditional_operations_no_suppression must be of a nullable type.
Sonek ! işlecinin çalışma zamanı etkisi yoktur; temel alınan ifadenin sonucunu değerlendirir.The postfix ! operator has no runtime effect - it evaluates to the result of the underlying expression. Tek rolü, ifadenin null durumunu "Not null" olarak değiştirmek ve kullanım sırasında verilen uyarıları sınırlamak içindir.Its only role is to change the null state of the expression to "not null", and to limit warnings given on its use.
Null yapılabilir derleyici yönergeleriNullable compiler directives
#nullable yönergeler null yapılabilir ek açıklama ve uyarı bağlamlarını denetler.#nullable directives control the nullable annotation and warning contexts.
pp_directive
: ...
| pp_nullable
;
pp_nullable
: whitespace? '#' whitespace? 'nullable' whitespace nullable_action (whitespace nullable_target)? pp_new_line
;
nullable_action
: 'disable'
| 'enable'
| 'restore'
;
nullable_target
: 'warnings'
| 'annotations'
;
#pragma warning yönergeler null yapılabilir uyarı bağlamını değiştirmeye izin verecek şekilde genişletilir:#pragma warning directives are expanded to allow changing the nullable warning context:
pragma_warning_body
: ...
| 'warning' whitespace warning_action whitespace 'nullable'
;
Örnek:For example:
#pragma warning disable nullable
Null yapılabilir bağlamlarNullable contexts
Her kaynak kodu satırında null yapılabilir bir ek açıklama bağlamı ve null yapılabilir uyarı bağlamı vardır.Every line of source code has a nullable annotation context and a nullable warning context. Bu denetim, null yapılabilir ek açıklamaların etkin olup olmadığını ve null olabilme uyarılarının verilip verilmediğini denetler.These control whether nullable annotations have effect, and whether nullability warnings are given. Verilen bir çizginin ek açıklama bağlamı devre dışı veya etkin.The annotation context of a given line is either disabled or enabled. Verilen bir satırın uyarı bağlamı devre dışı veya etkin değil.The warning context of a given line is either disabled or enabled.
Her iki içerik de proje düzeyinde (C# kaynak kodu dışında) veya bir kaynak dosyasındaki herhangi bir yerde, #nullable ön işlemci yönergeleri aracılığıyla belirtilebilir.Both contexts can be specified at the project level (outside of C# source code), or anywhere within a source file via #nullable pre-processor directives. Hiçbir proje düzeyi ayarı sağlanmazsa, varsayılan olarak her iki bağlam da devre dışı bırakılır.If no project level settings are provided the default is for both contexts to be disabled.
#nullableYönergesi, kaynak metin içindeki ek açıklamaları ve uyarı bağlamlarını denetler ve proje düzeyi ayarlarından önceliklidir.The #nullable directive controls the annotation and warning contexts within the source text, and take precedence over the project-level settings.
Bir yönerge, diğer bir yönerge tarafından geçersiz kılınana kadar veya kaynak dosyanın sonuna kadar, sonraki kod satırları için denetim bağlamını ayarlar.A directive sets the context(s) it controls for subsequent lines of code, until another directive overrides it, or until the end of the source file.
Yönergelerin etkisi aşağıdaki gibidir:The effect of the directives is as follows:
#nullable disable: Nullable ek açıklama ve uyarı bağlamlarını devre dışı olarak ayarlar#nullable disable: Sets the nullable annotation and warning contexts to disabled#nullable enable: Null yapılabilir ek açıklama ve uyarı bağlamlarını etkin olarak ayarlar#nullable enable: Sets the nullable annotation and warning contexts to enabled#nullable restore: Proje ayarlarına Nullable ek açıklama ve uyarı bağlamlarını geri yükler#nullable restore: Restores the nullable annotation and warning contexts to project settings#nullable disable annotations: Nullable ek açıklama bağlamını devre dışı olarak ayarlar#nullable disable annotations: Sets the nullable annotation context to disabled#nullable enable annotations: Null yapılabilir ek açıklama bağlamını etkin olarak ayarlar#nullable enable annotations: Sets the nullable annotation context to enabled#nullable restore annotations: Null yapılabilir ek açıklama bağlamını proje ayarlarına geri yükler#nullable restore annotations: Restores the nullable annotation context to project settings#nullable disable warnings: Nullable uyarı bağlamını devre dışı olarak ayarlar#nullable disable warnings: Sets the nullable warning context to disabled#nullable enable warnings: Null yapılabilir uyarı bağlamını etkin olarak ayarlar#nullable enable warnings: Sets the nullable warning context to enabled#nullable restore warnings: Proje ayarlarına Nullable uyarı bağlamını geri yükler#nullable restore warnings: Restores the nullable warning context to project settings
Türlerin null olabilme sayısıNullability of types
Verili bir tür üç adet null değer içerebilir: zorunlulukou, Nullable ve null yapılabilir.A given type can have one of three nullabilities: oblivious, nonnullable, and nullable.
Null olamayan türler, kendisine olası bir değer atandığında uyarılara neden olabilir null .Nonnullable types may cause warnings if a potential null value is assigned to them. Ancak, Zorunluluvou ve null yapılabilir türler, "null atanabilir" ve null uyarılar olmadan bunlara atanmış değerler içerebilir.Oblivious and nullable types, however, are "null-assignable" and can have null values assigned to them without warnings.
Zorunluluvou ve null yapılamayan türlerin değerleri uyarı vermeden bağlanabilir veya atanabilir.Values of oblivious and nonnullable types can be dereferenced or assigned without warnings. Ancak, null yapılabilir türlerin değerleri, "null olarak çıkarılıyor" ve doğru null denetimi yapılmadan başvurulmadan veya atanmadığı zaman uyarı oluşmasına neden olabilir.Values of nullable types, however, are "null-yielding" and may cause warnings when dereferenced or assigned without proper null checking.
Null değerli bir türün varsayılan null durumu "Belki null" veya "Belki default" dir.The default null state of a null-yielding type is "maybe null" or "maybe default". Null olmayan bir türün varsayılan null durumu "Not null" olarak ayarlanır.The default null state of a non-null-yielding type is "not null".
Tür türü ve null yapılabilir ek açıklama bağlamı, null olabilme değerini belirlemede oluşur:The kind of type and the nullable annotation context it occurs in determine its nullability:
- Null yapılamayan bir değer türü
Sher zaman null atanamazA nonnullable value typeSis always nonnullable - Null yapılabilir değer türü
S?her zaman null yapılabilirA nullable value typeS?is always nullable CDevre dışı bir ek açıklama bağlamındaki açıklamalı olmayan bir başvuru türü , zorunluluvouAn unannotated reference typeCin a disabled annotation context is oblivious- Etkin olmayan bir
Cek açıklama bağlamındaki açıklamalı olmayan bir başvuru türü null atanamazAn unannotated reference typeCin an enabled annotation context is nonnullable - Null yapılabilir bir başvuru
C?türü null olabilir (ancak bir uyarı, devre dışı bir ek açıklama bağlamında istenebilir)A nullable reference typeC?is nullable (but a warning may be yielded in a disabled annotation context)
Ayrıca tür parametrelerinin kısıtlamaları hesaba alır:Type parameters additionally take their constraints into account:
TTüm kısıtlamaların (varsa) boş değer atanabilir türleri veyaclass?kısıtlama null değer atanabilir olduğunda bir tür parametresiA type parameterTwhere all constraints (if any) are either nullable types or theclass?constraint is nullableTEn az bir kısıtlamanın zorunluluvou veya null yapılamayan ya da ya dastructclassnotnullkısıtlamalarından biri olduğu tür parametresiA type parameterTwhere at least one constraint is either oblivious or nonnullable or one of thestructorclassornotnullconstraints is- devre dışı bir ek açıklama bağlamındaki yükümlülüğüoblivious in a disabled annotation context
- etkin olmayan bir ek açıklama bağlamında null değer atanamaznonnullable in an enabled annotation context
- Null yapılabilir bir tür
T?parametresi null olabilir, ancak bir değer türü değilse, devre dışı bir ek açıklama bağlamına bir uyarı gönderilirTA nullable type parameterT?is nullable, but a warning is yielded in a disabled annotation context ifTisn't a value type
Zorunluluvou ile null atanamazOblivious vs nonnullable
typeTürün son belirteci bu bağlam içinde olduğunda, belirli bir ek açıklama bağlamında bir durum gerçekleşmelidir.A type is deemed to occur in a given annotation context when the last token of the type is within that context.
Kaynak kodda verilen bir başvuru türünün C , yükümlülüğü veya null değer atanabilir olarak yorumlanıp bu kaynak kodun ek açıklama bağlamına bağlıdır.Whether a given reference type C in source code is interpreted as oblivious or nonnullable depends on the annotation context of that source code. Ancak, bir kez kurulduktan sonra bu türün bir parçası olarak değerlendirilir ve "genel tür bağımsız değişkenlerinin yerine geçen" gibi.But once established, it is considered part of that type, and "travels with it" e.g. during substitution of generic type arguments. Bu, türü gibi bir ek açıklama olsa ? da görünmez.It is as if there is an annotation like ? on the type, but invisible.
KısıtlamalarConstraints
Null yapılabilir başvuru türleri, genel kısıtlamalar olarak kullanılabilir.Nullable reference types can be used as generic constraints.
class? , "muhtemelen Nullable başvuru türü" olarak belirlenirken, class etkin bir ek açıklama bağlamında "Nullable başvuru türü" olduğunu belirten yeni bir kısıtlamadır.class? is a new constraint denoting "possibly nullable reference type", whereas class in an enabled annotation context denotes "nonnullable reference type".
default , bir başvuru veya değer türü olarak bilinen bir tür parametresi belirten yeni bir kısıtlamadır.default is a new constraint denoting a type parameter that isn't known to be a reference or value type. Yalnızca geçersiz kılınabilen ve açıkça uygulanan metotlarda kullanılabilir.It can only be used on overridden and explicitly implemented methods. Bu kısıtlamayla, T? için bir toplu değer olacak şekilde null yapılabilir bir tür parametresi anlamına gelir Nullable<T> .With this constraint, T? means a nullable type parameter, as opposed to being a shorthand for Nullable<T>.
notnull Nullable olmayan bir tür parametresini belirten yeni bir kısıtlamadır.notnull is a new constraint denoting a type parameter that is nonnullable.
Bir tür bağımsız değişkeninin veya kısıtlamanın null olabilme sayısı, türün Şu anda zaten olduğu durumlar dışında (null yapılabilir değer türleri kısıtlamayı karşılamıyor), türü kısıtlamayı karşılayıp karşılamadığını etkilemez struct .The nullability of a type argument or of a constraint does not impact whether the type satisfies the constraint, except where that is already the case today (nullable value types do not satisfy the struct constraint). Ancak, tür bağımsız değişkeni kısıtlamanın null olabilme gereksinimlerini karşılamadığı takdirde bir uyarı verilebilir.However, if the type argument does not satisfy the nullability requirements of the constraint, a warning may be given.
Null durum ve null izlemeNull state and null tracking
Belirli bir kaynak konumundaki her ifadenin null olarak değerlendirilip değerlendirilmediğini belirten null durumu vardır.Every expression in a given source location has a null state, which indicated whether it is believed to potentially evaluate to null. Null durumu "Not null", "Belki null" veya "Belki default" olabilir.The null state is either "not null", "maybe null", or "maybe default". Null durumu, null güvenli olmayan dönüştürmeler ve başvuru işlemleri hakkında bir uyarı verilip verilmeyeceğini belirlemekte kullanılır.The null state is used to determine whether a warning should be given about null-unsafe conversions and dereferences.
"Belki null" ve "Belki default" arasındaki ayrım hafif ve tür parametreleri için geçerlidir.The distinction between "maybe null" and "maybe default" is subtle and applies to type parameters. Ayrım, T "Belki null" durumuna sahip bir tür parametresinin değerin geçerli değerler etki alanında olduğu, T ancak geçerli değerin dahil olabileceği anlamına gelir null .The distinction is that a type parameter T which has the state "maybe null" means the value is in the domain of legal values for T however that legal value may include null. "Belki de varsayılan" olarak, değerin geçerli etki alanı değerlerinin dışında olabileceği anlamına gelir T .Where as a "maybe default" means that the value may be outside the legal domain of values for T.
Örnek:Example:
// The value `t` here has the state "maybe null". It's possible for `T` to be instantiated
// with `string?` in which case `null` would be within the domain of legal values here. The
// assumption though is the value provided here is within the legal values of `T`. Hence
// if `T` is `string` then `null` will not be a value, just as we assume that `null` is not
// provided for a normal `string` parameter
void M<T>(T t)
{
// There is no guarantee that default(T) is within the legal values for T hence the
// state *must* be "maybe-default" and hence `local` must be `T?`
T? local = default(T);
}
Değişkenler için null izlemeNull tracking for variables
Değişkenleri, alanları veya özellikleri belirten belirli ifadeler için null durum, bunlar üzerinde yapılan atamalara ve bunlar arasındaki denetim akışına göre yineleme arasında izlenir.For certain expressions denoting variables, fields or properties, the null state is tracked between occurrences, based on assignments to them, tests performed on them and the control flow between them. Bu, değişkenler için kesin atamanın izlenme biçimine benzer.This is similar to how definite assignment is tracked for variables. İzlenen ifadeler aşağıdaki biçimdeki olanlardır:The tracked expressions are the ones of the following form:
tracked_expression
: simple_name
| this
| base
| tracked_expression '.' identifier
;
Tanımlayıcılar alanları veya özellikleri gösterir.Where the identifiers denote fields or properties.
İzlenen değişkenler için null durum, erişilemeyen kodda "Not null" olarak ayarlanır.The null state for tracked variables is "not null" in unreachable code. Bu, tüm yerelleri kesin olarak atanacak şekilde ele almak gibi ulaşılamaz kodun etrafındaki diğer kararları izler.This follows other decisions around unreachable code like considering all locals to be definitely assigned.
Kesin atamaya benzer null durum geçişlerini açıklaDescribe null state transitions similar to definite assignment
İfadeler için null durumuNull state for expressions
Bir ifadenin null durumu, form ve türünden türetilir ve buna dahil edilen değişkenlerin null durumudur.The null state of an expression is derived from its form and type, and from the null state of variables involved in it.
Değişmez DeğerlerLiterals
Bir sabit değerin null durumu, null ifadenin hedef türüne bağlıdır.The null state of a null literal depends on the target type of the expression. Hedef türü bir başvuru türüyle kısıtlanmış bir tür parametresi ise, "Belki de varsayılan" olur.If the target type is a type parameter constrained to a reference type then it's "maybe default". Aksi takdirde "Belki de null" olur.Otherwise it is "maybe null".
Sabit değerin null durumu, default sabit değerin hedef türüne bağlıdır default .The null state of a default literal depends on the target type of the default literal. defaultHedef türüne sahip bir sabit değer, T ifadeyle aynı null durumuna sahip default(T) .A default literal with target type T has the same null state as the default(T) expression.
Diğer herhangi bir sabit değerin null durumu "Not null" olur.The null state of any other literal is "not null".
Basit adlarSimple names
Bir simple_name değer olarak sınıflandırılmadığından, null durumu "null değil" olur.If a simple_name is not classified as a value, its null state is "not null". Aksi takdirde, izlenen bir ifadedir ve null durumu bu kaynak konumda izlenen null durumundadır.Otherwise it is a tracked expression, and its null state is its tracked null state at this source location.
Üye erişimiMember access
Bir member_access değer olarak sınıflandırılmadığından, null durumu "null değil" olur.If a member_access is not classified as a value, its null state is "not null". Aksi halde, izlenen bir ifadesiyse, null durumu bu kaynak konumda izlenen null durumundadır.Otherwise, if it is a tracked expression, its null state is its tracked null state at this source location. Aksi halde, null durumu türünün varsayılan null durumudur.Otherwise its null state is the default null state of its type.
var person = new Person();
// The receiver is a tracked expression hence the member_access of the property
// is tracked as well
if (person.FirstName is not null)
{
Use(person.FirstName);
}
// The return of an invocation is not a tracked expression hence the member_access
// of the return is also not tracked
if (GetAnonymous().FirstName is not null)
{
// Warning: Cannot convert null literal to non-nullable reference type.
Use(GetAnonymous().FirstName);
}
void Use(string s)
{
// ...
}
public class Person
{
public string? FirstName { get; set; }
public string? LastName { get; set; }
private static Person s_anonymous = new Person();
public static Person GetAnonymous() => s_anonymous;
}
Çağırma ifadeleriInvocation expressions
Bir invocation_expression veya daha fazla özel null davranışı için bir veya daha fazla öznitelik ile tanımlanmış bir üyeyi çağırdıysanız, null durumu bu öznitelikler tarafından belirlenir.If an invocation_expression invokes a member that is declared with one or more attributes for special null behavior, the null state is determined by those attributes. Aksi takdirde, ifadenin null durumu, türünün varsayılan null durumudur.Otherwise the null state of the expression is the default null state of its type.
Öğesinin null durumu invocation_expression derleyici tarafından izlenmez.The null state of an invocation_expression is not tracked by the compiler.
// The result of an invocation_expression is not tracked
if (GetText() is not null)
{
// Warning: Converting null literal or possible null value to non-nullable type.
string s = GetText();
// Warning: Dereference of a possibly null reference.
Use(s);
}
// Nullable friendly pattern
if (GetText() is string s)
{
Use(s);
}
string? GetText() => ...
Use(string s) { }
Öğe erişimiElement access
element_access, Özel null davranışı için bir veya daha fazla öznitelik ile tanımlanmış bir dizin oluşturucuyu çağırır, null durumu bu öznitelikler tarafından belirlenir.If an element_access invokes an indexer that is declared with one or more attributes for special null behavior, the null state is determined by those attributes. Aksi takdirde, ifadenin null durumu, türünün varsayılan null durumudur.Otherwise the null state of the expression is the default null state of its type.
object?[] array = ...;
if (array[0] != null)
{
// Warning: Converting null literal or possible null value to non-nullable type.
object o = array[0];
// Warning: Dereference of a possibly null reference.
Console.WriteLine(o.ToString());
}
// Nullable friendly pattern
if (array[0] is {} o)
{
Console.WriteLine(o.ToString());
}
Temel erişimBase access
BKapsayan türün temel türünü belirtir, ile aynı base.I null durumuna sahip ((B)this).I ve base[E] aynı null durumuna sahip ((B)this)[E] .If B denotes the base type of the enclosing type, base.I has the same null state as ((B)this).I and base[E] has the same null state as ((B)this)[E].
Varsayılan ifadelerDefault expressions
default(T) türünün özelliklerine göre null durumu vardır T :default(T) has the null state based on the properties of the type T:
- Tür null yapılamayan bir tür ise null durumu "Not null" olurIf the type is a nonnullable type then it has the null state "not null"
- Aksi durumda tür bir parametre ise, "Belki de" varsayılan değeri null olurElse if the type is a type parameter then it has the null state "maybe default"
- Aksi takdirde "Belki null" null durumu vardırElse it has the null state "maybe null"
Null Koşullu ifadeler?.Null-conditional expressions ?.
Bir, null_conditional_expression ifade türüne göre null durumuna sahiptir.A null_conditional_expression has the null state based on the expression type. Bu, null_conditional_expression çağrılan üyenin orijinal türü değil, öğesinin türünü ifade eder:Note that this refers to the type of the null_conditional_expression, not the original type of the member being invoked:
- Tür null yapılabilir bir değer türünde ise null durumu "Belki null" olurIf the type is a nullable value type then it has the null state "maybe null"
- Eğer tür null yapılabilir bir tür parametresi ise, null durumu "Belki varsayılan" olurElse if the type is a nullable type parameter then it has the null state "maybe default"
- Aksi takdirde "Belki null" null durumu vardırElse it has the null state "maybe null"
Atama ifadeleriCast expressions
Bir atama ifadesi (T)E Kullanıcı tanımlı bir dönüştürmeyi çağırmazsa, ifadenin null durumu Kullanıcı tanımlı dönüştürme türü için varsayılan null durumdur.If a cast expression (T)E invokes a user-defined conversion, then the null state of the expression is the default null state for the type of the user-defined conversion. Aksi durumda:.Otherwise:
- Null
Tyapılamayan bir değer türü iseTnull "Not null" durumuna sahiptirIfTis a nonnullable value type thenThas the null state "not null" - Eğer null
Tyapılabilir bir değer türünde iseTnull durumu "Belki null" olurElse ifTis a nullable value type thenThas the null state "maybe null" - Aksi durumda,
Tbir tür parametresi olduğu formda null yapılabilir bir tür varsa,U?UT"Belki de" varsayılan değer "olabilir"Else ifTis a nullable type in the formU?whereUis a type parameter thenThas the null state "maybe default" - Eğer null
Tyapılabilir bir tür ise veEnull durumu "Belki null" veya "Belki default" içeriyorsa,Tnull durumu "Belki null" olurElse ifTis a nullable type, andEhas null state "maybe null" or "maybe default", thenThas the null state "maybe null" - Eğer
Tbir tür parametresidir veEnull durumu "Belki null" veya "Belki varsayılan" varsa,Tnull durumu "Belki varsayılan" olurElse ifTis a type parameter, andEhas null state "maybe null" or "maybe default", thenThas the null state "maybe default" - Else
T, şu şekilde aynı null durumuna sahipEElseThas the same null state asE
Birli ve ikili işleçlerUnary and binary operators
Birli veya ikili işleç Kullanıcı tanımlı bir işleci çağırmazsa, ifadenin null durumu Kullanıcı tanımlı işlecin türü için varsayılan null durumdur.If a unary or binary operator invokes an user-defined operator then the null state of the expression is the default null state for the type of the user-defined operator. Aksi takdirde, ifadenin null durumudur.Otherwise it is the null state of the expression.
Dizeler ve temsilciler üzerinde ikili için yapılacak özel bir şey + var mı?Something special to do for binary + over strings and delegates?
Await ifadeleriAwait expressions
Null durumu, await E türünün varsayılan null durumudur.The null state of await E is the default null state of its type.
as işleciThe as operator
Bir ifadenin null durumu, E as T öncelikle türün özelliklerine bağlıdır T .The null state of an E as T expression depends first on properties of the type T. Türü null atanamaz ise T null durumu "Not null" olur.If the type of T is nonnullable then the null state is "not null". Aksi takdirde, null durumu tür türüne dönüştürme türüne bağlıdır E T :Otherwise the null state depends on the conversion from the type of E to type T:
- Dönüştürme bir kimlik, paketleme, örtük başvuru veya örtük null yapılabilir dönüştürme ise null durumu
EIf the conversion is an identity, boxing, implicit reference, or implicit nullable conversion, then the null state is the null state ofE - Eğer
Tbir tür parametresi ise, null durumu "Belki varsayılan" olurElse ifTis a type parameter then it has the null state "maybe default" - Aksi takdirde "Belki null" null durumu vardırElse it has the null state "maybe null"
Null birleşim işleciThe null-coalescing operator
E1 ?? E2Öğesinin null durumu,E2The null state of E1 ?? E2 is the null state of E2
Koşullu işleçThe conditional operator
Null durumu, E1 ? E2 : E3 ve ' nin null durumuna dayalıdır E2 E3 :The null state of E1 ? E2 : E3 is based on the null state of E2 and E3:
- Her ikisi de "null değil" ise null durumu "Not null" olurIf both are "not null" then the null state is "not null"
- Else "Belki de varsayılan" ise, null durumu "Belki varsayılan" olurElse if either is "maybe default" then the null state is "maybe default"
- Aksi durumda null durumu "Not null"Else the null state is "not null"
Sorgu ifadeleriQuery expressions
Sorgu ifadesinin null durumu, türünün varsayılan null durumudur.The null state of a query expression is the default null state of its type.
Burada ek iş gerekliAdditional work needed here
Atama işleçleriAssignment operators
E1 = E2 ve E1 op= E2 E2 tüm örtük dönüştürmeler uygulandıktan sonra aynı null durumuna sahip.E1 = E2 and E1 op= E2 have the same null state as E2 after any implicit conversions have been applied.
Null durumu yayan ifadelerExpressions that propagate null state
(E), checked(E) ve unchecked(E) tümünün aynı null durumu ile aynı olması gerekir E .(E), checked(E) and unchecked(E) all have the same null state as E.
Hiçbir koşulda null olmayan ifadelerExpressions that are never null
Aşağıdaki ifade formlarının null durumu her zaman "Not null" dır:The null state of the following expression forms is always "not null":
thiserişmesinithisaccess- enterpolasyonlu dizelerinterpolated strings
newifadeler (nesne, temsilci, anonim nesne ve dizi oluşturma ifadeleri)newexpressions (object, delegate, anonymous object and array creation expressions)typeofifadelerdetypeofexpressionsnameofifadelerdenameofexpressions- Anonim işlevler (anonim yöntemler ve lambda ifadeleri)anonymous functions (anonymous methods and lambda expressions)
- null-forverme ifadelerinull-forgiving expressions
isifadelerdeisexpressions
İç içe işlevlerNested functions
İç içe geçmiş işlevler (Lambdalar ve yerel işlevler), yakalanan değişkenlerine karşılık olmak dışında yöntemler gibi değerlendirilir.Nested functions (lambdas and local functions) are treated like methods, except in regards to their captured variables. Bir lambda veya yerel işlev içindeki yakalanan bir değişkenin ilk durumu, söz konusu iç içe yerleştirilmiş işlevin veya lambda 'nin tüm "kullanımlarına" değişkenin Nullable durumunun kesişmesi olur.The initial state of a captured variable inside a lambda or local function is the intersection of the nullable state of the variable at all the "uses" of that nested function or lambda. Yerel bir işlevin kullanımı, bu işleve yapılan bir çağrıdır ya da bir temsilciye dönüştürülür.A use of a local function is either a call to that function, or where it is converted to a delegate. Lambda kullanımı, kaynakta tanımlanan noktasıdır.A use of a lambda is the point at which it is defined in source.
Tür çıkarımıType inference
null atanabilir örtük olarak yazılan yerel değişkenlernullable implicitly typed local variables
var başvuru türleri için açıklamalı bir tür ve değer türü olarak Kısıtlanmamış tür parametreleri.var infers an annotated type for reference types, and type parameters that aren't constrained to be a value type.
Örneğin:For instance:
- içinde
var s = "";varolarak algılanırstring?.invar s = "";thevaris inferred asstring?. - kısıtlanmış olmayan ' de
var t = new T();Tvarolarak algılanırT?.invar t = new T();with an unconstrainedTthevaris inferred asT?.
Genel tür çıkarımıGeneric type inference
Genel tür çıkarımı, gösterilen başvuru türlerinin null yapılabilir olup olmadığına karar vermenize yardımcı olmak için geliştirilmiştir.Generic type inference is enhanced to help decide whether inferred reference types should be nullable or not. Bu en iyi çabadır.This is a best effort. Null olabilme kısıtlamalarına ilişkin uyarılar verebilir ve seçilen aşırı yüklemenin Çıkarsanan türleri bağımsız değişkenlere uygulandığında null yapılabilir uyarılara yol açabilir.It may yield warnings regarding nullability constraints, and may lead to nullable warnings when the inferred types of the selected overload are applied to the arguments.
İlk aşamaThe first phase
Null yapılabilir başvuru türleri, aşağıda açıklandığı gibi ilk ifadelerden sınırlara akar.Nullable reference types flow into the bounds from the initial expressions, as described below. Ayrıca, ve gibi iki yeni tür sınır null default eklenmiştir.In addition, two new kinds of bounds, namely null and default are introduced. Amaçları, null default giriş ifadelerinde veya, aksi durumda olmasa bile, Çıkarsanan bir türün null yapılabilir olmasına neden olabilen, tekrarlamaları aracılığıyla ilerleyesağlamaktır.Their purpose is to carry through occurrences of null or default in the input expressions, which may cause an inferred type to be nullable, even when it otherwise wouldn't. Bu işlem, çıkarım işleminde "nullanlam" çekmek üzere geliştirilmiş null yapılabilir değer türleri için de çalışır.This works even for nullable value types, which are enhanced to pick up "nullness" in the inference process.
İlk aşamada hangi sınırların ekleneceğini belirlemek şu şekilde geliştirilmiştir:The determination of what bounds to add in the first phase are enhanced as follows:
Bir bağımsız değişkenin Ei bir başvuru türü varsa, U çıkarım için kullanılan tür, null durumunun Ei yanı sıra belirtilen tür olarak değişir:If an argument Ei has a reference type, the type U used for inference depends on the null state of Ei as well as its declared type:
- Belirtilen tür null yapılamayan bir başvuru türü
U0veya null olabilen bir başvuru türü iseU0?If the declared type is a nonnullable reference typeU0or a nullable reference typeU0?then- null durumu
Ei"null değil" iseU,U0if the null state ofEiis "not null" thenUisU0 - null durumu
Ei"Belki null"UiseU0?if the null state ofEiis "maybe null" thenUisU0?
- null durumu
- Aksi takdirde
Ei, tanımlı bir tür varsa,UBu türOtherwise ifEihas a declared type,Uis that type - Aksi takdirde
Ei,nullUözel bir sınırdırnullOtherwise ifEiisnullthenUis the special boundnull - Aksi takdirde
Ei,defaultUözel bir sınırdırdefaultOtherwise ifEiisdefaultthenUis the special bounddefault - Aksi takdirde hiçbir çıkarım yapılmaz.Otherwise no inference is made.
Tam, üst sınır ve alt sınırExact, upper-bound and lower-bound inferences
Tür U olarak türü, türü V null olan V bir başvuru türü ise, V0? V0 V aşağıdaki yan tümcelerde yerine kullanılır.In inferences from the type U to the type V, if V is a nullable reference type V0?, then V0 is used instead of V in the following clauses.
VDüzeltilmeyen tür değişkenlerinden biri ise,Udaha önce olduğu gibi tam, üst veya alt sınır olarak eklenirIfVis one of the unfixed type variables,Uis added as an exact, upper or lower bound as before- Aksi takdirde,
Unullveya isedefault, çıkarımı yapılmazOtherwise, ifUisnullordefault, no inference is made - Aksi halde,
Unull yapılabilir bir başvuru türü iseU0?,U0Usonraki yan tümcelerde yerine kullanılır.Otherwise, ifUis a nullable reference typeU0?, thenU0is used instead ofUin the subsequent clauses.
Temelde, sabit olmayan tür değişkenlerinden biri ile ilgili olan null değer alabilme, kendi sınırlarına göre korunur.The essence is that nullability that pertains directly to one of the unfixed type variables is preserved into its bounds. Kaynak ve hedef türleri için ek olarak, diğer yandan null değer alabilme yok sayılır.For the inferences that recurse further into the source and target types, on the other hand, nullability is ignored. Bu, eşleşmeyebilir veya eşleşmeyebilir, ancak daha sonra aşırı yükleme seçilir ve uygulanırsa bir uyarı gönderilir.It may or may not match, but if it doesn't, a warning will be issued later if the overload is chosen and applied.
öğesini düzeltmeFixing
Spec Şu anda birden çok sınır birbirlerine dönüştürülebilir ancak farklılık belirten ne olduğunu açıklayan iyi bir iş gerçekleştirmez.The spec currently does not do a good job of describing what happens when multiple bounds are identity convertible to each other, but are different. Bu durum ve arasında object , dynamic yalnızca öğe adlarında farklı olan türler arasında, oluşturulan türler arasında ve artık C C? başvuru türleri arasında olabilir.This may happen between object and dynamic, between tuple types that differ only in element names, between types constructed thereof and now also between C and C? for reference types.
Ayrıca, giriş ifadelerinden sonuç türüne "nulltik" öğesini yaymaya ihtiyacımız vardır.In addition we need to propagate "nullness" from the input expressions to the result type.
Bunları işlemek için şu anda, düzeltmek üzere daha fazla aşama ekleyeceğiz:To handle these we add more phases to fixing, which is now:
- Tüm sınırlardaki tüm türleri aday olarak toplayın, her türlü
?null yapılabilir başvuru türünden kaldırmaGather all the types in all the bounds as candidates, removing?from all that are nullable reference types - Tam, alt ve üst sınırların gereksinimlerine göre adayları ortadan kaldırın (tutma
nullvedefaultsınırlar)Eliminate candidates based on requirements of exact, lower and upper bounds (keepingnullanddefaultbounds) - Tüm diğer adaylar için örtük dönüştürmesi olmayan adayları ortadan kaldırınEliminate candidates that do not have an implicit conversion to all the other candidates
- Kalan adayların hepsi bir diğeri için kimlik dönüştürmeleri yoksa, tür çıkarımı başarısız olurIf the remaining candidates do not all have identity conversions to one another, then type inference fails
- Kalan adayları aşağıda açıklandığı gibi birleştirinMerge the remaining candidates as described below
- Elde edilen aday bir başvuru türü veya null yapılamayan bir değer türü ise ve Tüm kesin sınırlar veya alt limitler null yapılabilir değer türlerdir, null yapılabilir başvuru türleri ya da bu, sonuç olarak null
nulldefault?değer türü veya başvuru türü haline gelir.If the resulting candidate is a reference type or a nonnullable value type and all of the exact bounds or any of the lower bounds are nullable value types, nullable reference types,nullordefault, then?is added to the resulting candidate, making it a nullable value type or reference type.
Birleştirme iki aday türü arasında tanımlanır.Merging is described between two candidate types. Bu, bir geçişli ve sorun olduğundan, adaylar aynı nihai sonuçla herhangi bir sırada birleştirilebilir.It is transitive and commutative, so the candidates can be merged in any order with the same ultimate result. İki aday türü birbirlerine dönüştürülebilir değilse, bu tanımsız olur.It is undefined if the two candidate types are not identity convertible to each other.
Merge işlevi iki aday türü ve bir yön ( + veya) alır - :The Merge function takes two candidate types and a direction (+ or -):
- Birleştir(
T,T, d) = TMerge(T,T, d) = T - Merge(
S,T?, + ) = merge(S?,T, + ) = merge(S,T, + )?Merge(S,T?, +) = Merge(S?,T, +) = Merge(S,T, +)? - Merge(
S,T?, - ) = merge(S?,T, - ) = merge(S,T, - )Merge(S,T?, -) = Merge(S?,T, -) = Merge(S,T, -) - Birleştir(
C<S1,...,Sn>,C<T1,...,Tn>, + ) =C<Birleştir(S1,T1, D1),...,birleştirme(,,SnTnDN)>, buradaMerge(C<S1,...,Sn>,C<T1,...,Tn>, +) =C<Merge(S1,T1, d1),...,Merge(Sn,Tn, dn)>, wheredi= +i' th Type parametresiC<...>birlikte değişken isedi= + if thei'th type parameter ofC<...>is covariantdi= -i' th Type parametresiC<...>iytra veya sabit isedi= - if thei'th type parameter ofC<...>is contra- or invariant
- Birleştir(
C<S1,...,Sn>,C<T1,...,Tn>, - ) =C<Birleştir(S1,T1, D1),...,birleştirme(,,SnTnDN)>, buradaMerge(C<S1,...,Sn>,C<T1,...,Tn>, -) =C<Merge(S1,T1, d1),...,Merge(Sn,Tn, dn)>, wheredi= -i' th Type parametresiC<...>birlikte değişken isedi= - if thei'th type parameter ofC<...>is covariantdi= +i' th Type parametresiC<...>iytra veya sabit isedi= + if thei'th type parameter ofC<...>is contra- or invariant
- Birleştir(
(S1 s1,..., Sn sn),(T1 t1,..., Tn tn), d) =(birleştirme(S1,T1, d)n1,...,birleştirmeSnTnnn)(,, d), buradaMerge((S1 s1,..., Sn sn),(T1 t1,..., Tn tn), d) =(Merge(S1,T1, d)n1,...,Merge(Sn,Tn, d)nn), whereni``sivetifarklıysa yok veya her ikisi de yoksaniis absent ifsiandtidiffer, or if both are absentni,sisivetiaynı iseniissiifsiandtiare the same
- Merge(
object,dynamic) = merge(dynamic,object) =dynamicMerge(object,dynamic) = Merge(dynamic,object) =dynamic