Implicit conversions are a C# construct and are not available through reflection. Additionally, setting a field or property through reflection means that you must provide the appropriate type up front. You can attempt to circumvent this by using a custom TypeConverter (or some other means of custom conversion) to help convert your types at runtime prior to using reflection. Here's a rough example of a TypeConverter implementation.
public class MyIdTypeConverter : TypeConverter
{
public override object ConvertFrom(ITypeDescriptorContext context,
System.Globalization.CultureInfo culture,
object value)
{
if (value is int)
return new MyId((int)value);
else if (value is MyId)
return value;
return base.ConvertFrom(context, culture, value);
}
}
Here's the type that we would be trying to set the Custom
property on.
public class Container
{
[TypeConverter(typeof(MyIdTypeConverter))]
public MyId Custom { get; set; }
}
The code to call it would have to check the attribute and perform the conversion ahead of time, after which it could call SetValue
.
var instance = new Container();
var type = typeof(Container);
var property = type.GetProperty("Custom");
var descriptor = TypeDescriptor.GetProperties(instance)["Custom"];
var converter = descriptor.Converter;
property.SetValue(instance, converter.ConvertFrom(15), null);
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…