Reflection to find out if the property has an option type

I fill in some fields of objects with data using reflection. Since my object is of type F #, it has several fields Option. In case of option

property.SetValue(object, newValue)

reasonably fails because he needs

property.SetValue(object, Some(newValue))

Therefore, I am trying to figure out if a property has a type Option. I can do it like this:

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

But there must be some better way, right? And I have to say that it is strange to me that there is no method IsOptionin FSharpType.

+4
source share
1 answer

You can use something like this:

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

, GetGenericTypeDefinition - . typedefof - , . Option<> - . , , .

+7

All Articles