Reflection to find out if property is of option type

匆匆过客 提交于 2019-12-12 11:03:07

问题


I am filling some object's fields with data using reflection. As my object is of F# type, it has some Option fields. In case of option

property.SetValue(object, newValue)

reasonably fails, because it needs

property.SetValue(object, Some(newValue))

Hence, I am trying to find out if a property is of type Option. I can do it like this:

let isOption (p:PropertyInfo) = p.PropertyType.Name.StartsWith("FSharpOption")

But there must be some better way, must it not? And I must say it is strange to me that there's no method IsOption in FSharpType.


回答1:


You can use something like this:

let isOption (p:PropertyInfo) = 
    p.PropertyType.IsGenericType &&
    p.PropertyType.GetGenericTypeDefinition() = typedefof<Option<_>>

Basically, GetGenericTypeDefinition returns the generic type of the property without any type parameters. And typedefof does something very similar, only using compile-time type information. In this case, it will return Option<>, without any parameters. You can then simply compare them to see if they are the same type.



来源:https://stackoverflow.com/questions/20696262/reflection-to-find-out-if-property-is-of-option-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!