Ho una classe di dettagli utente
public partial class UserDetails
{
public int? Level { get; set; }
public string Unit { get; set; }
public string Bio { get; set; }
public bool? Gender { get; set; }
public int? Mobile { get; set; }
public string Photo { get; set; }
}
Sto scrivendo un metodo di aggiornamento:
public bool UpdateDetails(string userId, UserProperties updateProperty, string value)
{
switch(updateProperty)
{
case UserProperties.Unit:
details.Unit = value;
break;
case UserProperties.Photo:
details.Photo = value;
break;
default:
throw new Exception("Unknown User Detail property");
}
Posso fare qualcosa di simile alla proprietà dinamica in JavaScript? per esempio
var details = new UserDetails();
details["Unit"] = value;
Aggiornare
A partire dall'anno 2019! Che ne dici di provare a usare questa nuova funzionalità ?! Metodo DynamicObject DynamicObject.TrySetMember (SetMemberBinder, Object)
Sto cercando di capire come scriverlo.
È possibile farlo tramite la riflessione per le proprietà esistenti sull'oggetto.
C # ha una funzione chiamata Indexer . È possibile estendere il codice in questo modo per consentire il comportamento previsto.
public partial class UserDetails
{
public int? Level { get; set; }
public string Unit { get; set; }
public string Bio { get; set; }
public bool? Gender { get; set; }
public int? Mobile { get; set; }
public string Photo { get; set; }
// Define the indexer to allow client code to use [] notation.
public object this[string propertyName]
{
get {
PropertyInfo prop = this.GetType().GetProperty(propertyName);
return prop.GetValue(this);
}
set {
PropertyInfo prop = this.GetType().GetProperty(propertyName);
prop.SetValue(this, value);
}
}
}
Oltre a ciò, se non si conoscono le proprietà in fase di esecuzione, è possibile utilizzare il tipo dinamico .