我继承了一些试图设置属性的代码:
object target = ... // some instance on which we want to set a property object value = ... // some value - in this case, a string var propertyInfo = ... // some property of target - in this case, not a string try { propertyInfo.SetValue(obj, value, null); } catch (ArgumentException) { // We go off and look for our own way of converting between // the type of value and the type of the property. }
在当前使用中,异常被捕获并抛出很多,所以我想首先进行检查:
if (propertyInfo.PropertyType.IsAssignableFrom(value.GetType()) { // Try/catch as above } else { // Do the manual conversion as if the exception had been thrown. }
这运行得更快.但是,我唯一担心的是,对于某些实际上会成功的类型,IsAssignableFrom
可能会返回.(这会导致我们在不需要时查找手动转换,并且可能无法完全设置值.)false
SetValue
规格SetValue
说
value无法转换为PropertyType的类型
这与可分配性不完全相同.
(如果在失败的情况下IsAssignableFrom
返回,那很好 - 手动转换仍然会发生.)true
SetValue
有人可以向我确认这是否可行?