Come impostare un valore predefinito usando & # 8220; stile corto & # 8221; proprietà in VS2008 (Proprietà automatiche)?

StackOverflow https://stackoverflow.com/questions/206611

Domanda

Come posso impostare un valore predefinito su una proprietà definita come segue:

public int MyProperty { get; set; }

Questo sta usando " prop " [tab] [tab] in VS2008 (frammento di codice).

È possibile senza ricorrere al "vecchio modo"?:

private int myProperty = 0; // default value
public int MyProperty
{
    get { return myProperty; }
    set { myProperty = value; }
}

Grazie per il tuo tempo. Cordiali saluti.

È stato utile?

Soluzione

Basta impostare " default " valore all'interno del costruttore.

public class Person
{
   public Person()
   {
       this.FirstName = string.Empty;
   }

   public string FirstName { get; set; }
}

Inoltre, si chiamano Proprietà automatiche.

Altri suggerimenti

La mia preferenza sarebbe quella di fare le cose "alla vecchia maniera", piuttosto che init nel costruttore. Se successivamente aggiungi un altro costruttore, dovrai essere sicuro di chiamare il primo da esso o le tue proprietà non saranno inizializzate.

Anche se questo è un vecchio thread, vorrei aggiungere un nuovo modo implementato in C # > Vers. 6:

https://msdn.microsoft.com/de-de/library/ bb384054.aspx

public int MyInt { get; set; } = 0;
public string MyString { get; set; } = "Lorem Ipsum";

[DefaultValue (" MyFirstName ")] stringa pubblica FirstName {get; impostato; }

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top