您可以使用类型转换器(无错误检查):
Ship ship = new Ship();
string value = "5.5";
var property = ship.GetType().GetProperty("Latitude");
var convertedValue = property.Converter.ConvertFrom(value);
property.SetValue(self, convertedValue);
在组织代码方面,你可以创建一种混合类型 mixin,这将导致如下的代码:
Ship ship = new Ship();
ship.SetPropertyAsString("Latitude", "5.5");
这可以通过以下代码实现:
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
可以被多个不同的类重复使用。
您还可以创建自己的自定义类型转换器,并将其附加到您的属性或类中:
public class Ship : MPropertyAsStringSettable {
public Latitude Latitude { get; set; }
}
[TypeConverter(typeof(LatitudeConverter))]
public class Latitude { ... }