Vous pouvez utiliser un convertisseur de type (aucune vérification d'erreur):
Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
En termes d'organisation du code, vous pourriez créer une sorte de mixin qui aboutirait à un code semblable à ceci:
Ship ship = new Ship();
ship.SetPropertyAsString("Latitude", "5.5");
Cela serait réalisé avec ce code:
public interface MPropertyAsStringSettable { }
public static class PropertyAsStringSettable {
public static void SetPropertyAsString(
this MPropertyAsStringSettable self, string propertyName, string value) {
var property = TypeDescriptor.GetProperties(self)[propertyName];
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
}
}
public class Ship : MPropertyAsStringSettable {
public double Latitude { get; set; }
// ...
}
MPropertyAsStringSettable
peut être réutilisé pour de nombreuses classes différentes.
Vous pouvez également créer vos propres convertisseurs de type personnalisés à attacher à vos propriétés ou classes:
public class Ship : MPropertyAsStringSettable {
public Latitude Latitude { get; set; }
// ...
}
[TypeConverter(typeof(LatitudeConverter))]
public class Latitude { ... }
1 votes
Question pour vous: est-ce que cela fait partie d'une solution ORM personnalisée?