Вы можете использовать конвертер типа (без проверки ошибок):
Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
С точки зрения организации кода, вы можете создать kind-of mixin, что привело бы в коде как это:
Ship ship = new Ship();
ship.SetPropertyAsString("Latitude", "5.5");
Это было бы ieved с этим кодом:
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
может быть повторно использован для различных классов.
Вы также можете создать свой собственный type converters прикрепить к свойствам или классам:
public class Ship : MPropertyAsStringSettable {
public Latitude Latitude { get; set; }
// ...
}
[TypeConverter(typeof(LatitudeConverter))]
public class Latitude { ... }
Вопрос для вас: эта часть пользовательского решения ORM? – user3308043