Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/fsharp/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reflection F#相当于C#类型的(IEnumerable<;>;)_Reflection_F#_C# To F# - Fatal编程技术网

Reflection F#相当于C#类型的(IEnumerable<;>;)

Reflection F#相当于C#类型的(IEnumerable<;>;),reflection,f#,c#-to-f#,Reflection,F#,C# To F#,我有一段代码,需要弄清楚给定类型是否实现了IEnumerable(我不关心t) 我已经试过了(t:System.Type,以防万一) let interfaces=t.GetInterfaces() 设枚举数= 接口。任何(有趣的t-> t、 GetGenericTypeDefinition()=typeof ) 但是,这不会编译(编译程序不喜欢这种方式)。然后我试着 let interfaces = t.GetInterfaces() let enumerbale = inter

我有一段代码,需要弄清楚给定类型是否实现了
IEnumerable
(我不关心t)

我已经试过了(
t:System.Type
,以防万一)

let interfaces=t.GetInterfaces()
设枚举数=
接口。任何(有趣的t->
t、 GetGenericTypeDefinition()=typeof
) 
但是,这不会编译(编译程序不喜欢这种方式)。然后我试着

let interfaces = t.GetInterfaces()
let enumerbale = 
    interfaces.Any(fun t -> 
        t.GetGenericTypeDefinition() = typeof<IEnumerable<'a>>
    )
let interfaces=t.GetInterfaces()
设枚举数=
接口。任何(有趣的t->
t、 GetGenericTypeDefinition()=typeof这应该可以:

typedefof<System.IEnumerable<_>>
据我所知,F#与C#的
typeof(IEnumerable)
没有任何等价物。这是因为,这是C#明确支持的一种特殊语法。在F#中,
typeof
是一个普通函数,类型参数必须是完全指定的类型。您可以通过编程方式获得一个通用类型定义,如下所示:

let t = typeof<IEnumerable<obj>>
let genericT = t.GetGenericTypeDefinition()
设t=typeof
让genericT=t.GetGenericTypeDefinition()

您使用
IEnumerable解决方案的问题我不想指出,这个问题是在


感谢您对“您的解决方案帮我避免了另一个问题:)的澄清,错误消息“由于对象的当前状态而不受支持”,这是一种表示不能在非泛型类型上调用getgenerictypedefinitionón的方式。如果泛型类型受到约束,这将变得异常丑陋。在我的例子中,当'T:struct'和'T:>Enum
时,约束是
,因此编译器在为类型推断变量应用默认类型'int'时,会抱怨
\uu
错误FS0071类型约束不匹配。类型“int”与类型“枚举”不兼容,考虑添加其他类型约束。< /代码>
(fun t -> t.IsGenericType && (t.GetGenericTypeDefinition() = typedefof<_ seq>))
let t = typeof<IEnumerable<obj>>
let genericT = t.GetGenericTypeDefinition()