Errore del compilatore CS1917

Aggiornamento: novembre 2007

Messaggio di errore

Impossibile assegnare i membri del campo di sola lettura 'name' di tipo 'struct name' con un inizializzatore di oggetti perché è di un tipo valore.
Members of read-only field 'name' of type 'struct name' cannot be assigned with an object initializer because it is of a value type.

I campi di sola lettura che sono tipi valore possono essere assegnati solo in un costruttore.

Per correggere l'errore

  • Impostare la struttura su un tipo classe.

  • Inizializzare la struttura con un costruttore.

Esempio

Nel codice seguente viene generato l'errore CS1917:

// cs1917.cs
class CS1917
{
    public struct TestStruct
    {
        public int i;
    }
    public class C
    {
        public readonly TestStruct str = new TestStruct();
        public static int Main()
        {
            C c = new C { str = { i = 1 } }; // CS1917
            return 0;
        }
    }
}