Reflection to find out if property is of option ty

2019-06-22 14:15发布

问题:

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.



标签: reflection f#