why a generic struct parameterized by blittable type is not an unmanaged type?(为什么由blittable类型参数化的泛型结构不是非托管类型?)
问题描述
我有一个函数foo,它接受非托管类型,然后我创建了一个泛型结构,它要求类型参数是非托管的:
[<Struct>]
type Vector4<'T when 'T:unmanaged> =
val x : 'T
val y : 'T
val z : 'T
val w : 'T
new (x, y, z, w) = { x = x; y = y; z = z; w = w }
let foo<'T when 'T:unmanaged> (o:'T) =
printfn "%A" o
printfn "%d" sizeof<'T>
let bar() =
let o = Vector4<float32>(1.0f, 2.0f, 3.0f, 4.0f)
foo o // here has error
但我遇到编译错误:
Error 4 A generic construct requires that the type 'Vector4<float32>' is an unmanaged type
我检查了MSDN,它是:
提供的类型必须是非托管类型。非托管类型为 某些原语类型(sbyte、byte、char、nativeint, Unativeint,浮动32,浮动,int16,uint16,int32,uint32,int64, Uint64或DECIMAL)、枚举类型、本机类型或非泛型 结构,其字段均为非托管类型。
为什么需要blittable类型参数的泛型结构不是非托管类型?
推荐答案
互操作不支持泛型类型:[1],[2]
COM模型不支持泛型类型的概念。 因此,泛型类型不能直接用于COM互操作。
很遗憾,键入别名在这种情况下无济于事:
[<Struct>]
[<StructLayout(LayoutKind.Sequential)>]
type Vector4<'T when 'T:unmanaged> =
val x : 'T
val y : 'T
val z : 'T
val w : 'T
new (x, y, z, w) = { x = x; y = y; z = z; w = w }
type Vector4float = Vector4<float32>
let inline foo<'T when 'T:unmanaged> (o:'T) =
printfn "%A" o
printfn "%d" sizeof<'T>
let bar() =
let o = new Vector4float(1.0f, 2.0f, 3.0f, 4.0f)
foo o // A generic construct requires that the type 'Vector4float' is an unmanaged type
这篇关于为什么由blittable类型参数化的泛型结构不是非托管类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:为什么由blittable类型参数化的泛型结构不是非托管类型?
基础教程推荐
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
