Hedef türü belirtilmiş new ifadelerTarget-typed new expressions

  • [x] önerilir[x] Proposed
  • [x] prototipi[x] Prototype
  • [] Uygulama[ ] Implementation
  • [] Belirtimi[ ] Specification

ÖzetSummary

Tür bilindiğinde oluşturucular için tür belirtimi gerektirmeyin.Do not require type specification for constructors when the type is known.

MotivasyonMotivation

Türü çoğaltmadan alan başlatılmasına izin verin.Allow field initialization without duplicating the type.

Dictionary<string, List<int>> field = new() {
    { "item1", new() { 1, 2, 3 } }
};

Kullanımdan çıkarsanamıyor, türü dışarıda bırakabilirsiniz.Allow omitting the type when it can be inferred from usage.

XmlReader.Create(reader, new() { IgnoreWhitespace = true });

Türü yazarken bir nesne oluşturun.Instantiate an object without spelling out the type.

private readonly static object s_syncObj = new();

BelirtimSpecification

Yeni bir sözdizimsel form, object_creation_expression target_typed_new , türün isteğe bağlı olduğu kabul edilir.A new syntactic form, target_typed_new of the object_creation_expression is accepted in which the type is optional.

object_creation_expression
    : 'new' type '(' argument_list? ')' object_or_collection_initializer?
    | 'new' type object_or_collection_initializer
    | target_typed_new
    ;
target_typed_new
    : 'new' '(' argument_list? ')' object_or_collection_initializer?
    ;

Target_typed_new ifadesinin türü yok.A target_typed_new expression does not have a type. Ancak, ifadeden örtük dönüştürme olan yeni bir nesne oluşturma dönüştürmesi vardır. bu bir target_typed_new, her türe bir vardır.However, there is a new object creation conversion that is an implicit conversion from expression, that exists from a target_typed_new to every type.

Bir hedef türü verildiğinde T tür, T0 T öğesinin bir örneği ise temel tür olur T System.Nullable .Given a target type T, the type T0 is T's underlying type if T is an instance of System.Nullable. Aksi T0 halde T .Otherwise T0 is T. Türe dönüştürülen target_typed_new ifadesinin anlamı, T türü olarak belirten karşılık gelen bir object_creation_expression anlamı ile aynıdır T0 .The meaning of a target_typed_new expression that is converted to the type T is the same as the meaning of a corresponding object_creation_expression that specifies T0 as the type.

Bir target_typed_new birli veya ikili işlecin işleneni olarak kullanılıyorsa ya da bir nesne oluşturma dönüştürmesinin konusu olmadığı durumlarda kullanılıyorsa, derleme zamanı hatasıdır.It is a compile-time error if a target_typed_new is used as an operand of a unary or binary operator, or if it is used where it is not subject to an object creation conversion.

Açık sorun: temsilcilerin ve tanımlama gruplarının hedef tür olarak izin vermesi gerekir mi?Open Issue: should we allow delegates and tuples as the target-type?

Yukarıdaki kurallar temsilcileri (bir başvuru türü) ve tanımlama gruplarını (bir struct türü) içerir.The above rules include delegates (a reference type) and tuples (a struct type). Her iki tür de oluşturulabilir olsa da, tür ınable ise anonim bir işlev veya bir tanımlama grubu değişmez değeri zaten kullanılabilir.Although both types are constructible, if the type is inferable, an anonymous function or a tuple literal can already be used.

(int a, int b) t = new(1, 2); // "new" is redundant
Action a = new(() => {}); // "new" is redundant

(int a, int b) t = new(); // OK; same as (0, 0)
Action a = new(); // no constructor found

ÇeşitliMiscellaneous

Aşağıda, belirtimin sonuçları verilmiştir:The following are consequences of the specification:

  • throw new() izin veriliyor (hedef tür System.Exception )throw new() is allowed (the target type is System.Exception)
  • Target türü new ikili işleçlerle kullanılamaz.Target-typed new is not allowed with binary operators.
  • Hedeflenecek tür olmadığında buna izin verilmez: bir deyimde, bir ifadesinde, bir deyimi içinde, bir deyimindeki bir deyimde, bir ifadede, bir deyimde, bir deyimde, bir deyimde, bir deyimde, bir deyiminde, bir deyim içinde, bir deyimde, bir deyimde (), bir bir deyimde, foreach using await new { Prop = new() } lock sizeof fixed new().field someDynamic.Method(new()) is ??It is disallowed when there is no type to target: unary operators, collection of a foreach, in a using, in a deconstruction, in an await expression, as an anonymous type property (new { Prop = new() }), in a lock statement, in a sizeof, in a fixed statement, in a member access (new().field), in a dynamically dispatched operation (someDynamic.Method(new())), in a LINQ query, as the operand of the is operator, as the left operand of the ?? operator, ...
  • Ayrıca, bir olarak da buna izin verilmez ref .It is also disallowed as a ref.
  • Dönüştürme hedefleri olarak aşağıdaki tür türlere izin verilmezThe following kinds of types are not permitted as targets of the conversion
    • Sabit listesi türleri: new() çalışır ( new Enum() varsayılan değeri vermek için çalışır), ancak new(1) sabit listesi türlerinde hiçbir Oluşturucu yoktur.Enum types: new() will work (as new Enum() works to give the default value), but new(1) will not work as enum types do not have a constructor.
    • Arabirim türleri: Bu, COM türleri için ilgili oluşturma ifadesiyle aynı şekilde çalışır.Interface types: This would work the same as the corresponding creation expression for COM types.
    • Dizi türleri: dizilerin uzunluğu sağlamak için özel bir sözdizimi olması gerekir.Array types: arrays need a special syntax to provide the length.
    • dinamik: izin vermedik new dynamic() , bu nedenle new() dynamic hedef tür olarak izin vermedik.dynamic: we don't allow new dynamic(), so we don't allow new() with dynamic as a target type.
    • Tanımlama grupları: Bunlar, temel alınan türü kullanarak bir nesne oluşturma ile aynı anlama sahiptir.tuples: These have the same meaning as an object creation using the underlying type.
    • Object_creation_expression izin verilmeyen tüm diğer türler Ayrıca, örneğin işaretçi türleri hariç tutulur.All the other types that are not permitted in the object_creation_expression are excluded as well, for instance, pointer types.

BulunmaktadırDrawbacks

Hedef türsüz bazı sorunlar vardı new , ancak bu, son değişiklikler için yeni kategoriler oluşturur, ancak null ve default , ve bu önemli bir sorun olmamıştı.There were some concerns with target-typed new creating new categories of breaking changes, but we already have that with null and default, and that has not been a significant problem.

AlternatiflerAlternatives

Alan başlatılmasında yinelenmek için çok uzun olan türler hakkında şikayetlerden çoğu, türün kendisi değil tür bağımsız değişkenleri hakkında bilgi verebiliriz new Dictionary(...) . (ya da benzer) ve bağımsız değişken veya koleksiyon başlatıcıdan yerel olarak tür bağımsız değişkenleri çıkarsız.Most of complaints about types being too long to duplicate in field initialization is about type arguments not the type itself, we could infer only type arguments like new Dictionary(...) (or similar) and infer type arguments locally from arguments or the collection initializer.

SorularQuestions

  • İfade ağaçlarında kullanımları planlıyoruz mı?Should we forbid usages in expression trees? eşleşen(no)
  • Özellik bağımsız değişkenlerle nasıl etkileşime girer dynamic ?How the feature interacts with dynamic arguments? (özel bir işleme yok)(no special treatment)
  • IntelliSense nasıl çalışır new() ?How IntelliSense should work with new()? (yalnızca tek bir hedef türü olduğunda)(only when there is a single target-type)

Tasarım toplantılarıDesign meetings