2015-06-26 12 views
22

La mia comprensione è che ora sono consentiti i costruttori senza parametri nelle strutture.Costruttori senza parametri nelle strutture per C# 6

ma la seguente mi dà un errore di compilazione in VS 2015 Comunità

public struct Person 
{ 
    public string Name { get; } 
    public int Age { get; } 
    public Person(string name, int age) { Name = name; Age = age; } 
    public Person() : this("Jane Doe", 37) { } 
} 

errore: "Structs non può contenere costruttori senza parametri espliciti"

Qualcuno sa perché?

+0

Questo collegamento sembra mostrare che dovrebbe funzionare in C# 6 con VS 2015: http://www.c-sharpcorner.com/UploadFile/0e8478/parameterless-constructors-in-structs/ Non so perché non funzioni per te. –

+0

Ecco un altro articolo con alcune avvertenze: http://www.volatileread.com/Wiki/Index?id=1091 Ma niente per spiegare il tuo particolare problema. Hai verificato che il tuo progetto abbia come target il framework .NET 6.0 nelle impostazioni di Project? –

risposta

38

La funzione era presente nelle anteprime precedenti di C# 6.0, motivo per cui alcuni articoli ne parlano. Ma è stato rimosso e quindi non è presente nella versione distribuita con VS 2015 RC.

In particolare, la modifica è stata ripristinata in pull request #1106, con ulteriori informazioni sulla motivazione in issue #1029. Citando Vladimir Sadov:

As we performed more and more testing, we kept discovering cases where parameterless struct constructors caused inconsistent behavior in libraries or even in some versions of CLR.

[…]

After reconsidering the potential issues arising from breaking long standing assumptions, we decided it was best for our users to restore the requirement on struct constructors to always have formal parameters.

+0

Interessante: sebbene la funzione sia stata rimossa dal C#, è stata conservata in [tag: vb.net] e può essere utilizzata lì. L'esempio di codice OP convertito in VB (tutti i costruttori hanno il nome 'New' lì) funzionerà. – miroxlav

+0

@miroxlav [Non penso che sia vero.] (Http://stackoverflow.com/q/32179495/41071) – svick

+1

Oh capisco, anche se esplicitamente non dichiarato, questa discussione riguarda solo * quelli non statici *. I costruttori statici 'struct' non parametrici funzionano sia in C# che in VB. (Testato) – miroxlav

0

io non so perché, però, questo è consentito:

public struct Person 
{ 
    public string Name { get; } 
    public int Age { get; } 
    public Person(string name = null, int age = 0) { Name = name; Age = age; } 
} 

Vuol risolto il problema?

+6

Il costruttore definito non verrà chiamato se non si utilizzano parametri, vedere [qui] (https://stackoverflow.com/questions/27145633/unintuitive-behaviour-with-struct-initialization-and-default-arguments ? lq = 1) – gartenriese

Problemi correlati