反射以了解属性是否为选项类型 [英] Reflection to find out if property is of option type

查看:88
本文介绍了反射以了解属性是否为选项类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用反射将数据填充到某些对象的字段中.由于我的对象是F#类型,因此它具有一些Option字段.如果是

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))

因此,我试图找出某个属性是否为Option类型.我可以这样:

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")

但是必须有更好的方法,不是吗?我必须说,FSharpType中没有方法IsOption对我来说很奇怪.

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.

推荐答案

您可以使用以下内容:

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

基本上, 返回属性的通用类型,不带任何类型参数.并且 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.

这篇关于反射以了解属性是否为选项类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆