使用Lua中基于标志的.NET枚举

本文关键字:标志 NET 枚举 Lua 于标志 使用 | 更新日期: 2023-09-27 18:24:58

我正在使用LuaInterface for.NET创建Windows窗体对象。这工作得很好,除了一件事:

我想使用ControlAnchor属性使它们自动调整大小。如果我只设置其中一个Anchors(例如,只设置AnchorStyles.Top),它会起作用,但这实际上没有意义。我必须设置多个锚点,这是通过将它们与"逐位或"组合来完成的(或者只是通过数字相加)。

在VB.Net中,两者都工作:

Dim myLabel As New Label()
myLabel.Anchor = AnchorStyles.Top
myLabel.Anchor = AnchorStyles.Top + AnchorStyles.Left + _
                 AnchorStyles.Bottom + AnchorStyles.Right

在Lua,这确实有效:

luanet.load_assembly("System.Windows.Forms")
local WinForms = luanet.System.Windows.Forms
local myLabel = WinForms.Label()
myLabel.Anchor = WinForms.AnchorStyles.Top

但这条附加线路没有:

myLabel.Anchor = WinForms.AnchorStyles.Top + WinForms.AnchorStyles.Left + 
               WinForms.AnchorStyles.Bottom + WinForms.AnchorStyles.Right

它给了我以下错误:

LuaInterface.LuaException: attempt to perform arithmetic on
field 'Top' (a userdata value)

这在某种意义上是正确的,因为"LuaInterface将枚举值视为相应枚举类型的字段"(LuaInterface说:用Lua编写.NET CLR脚本)。


也不可能将值指定为数字:

myLabel.Anchor = 15    -- 15 = 8 + 4 + 2 + 1 = Top+Left+Right+Bottom

这一次,错误消息相当不具体:

LuaInterface.LuaException: function

我该如何解决这个问题?

是否有可能在Lua中将数字类型转换为正确的枚举类型

使用Lua中基于标志的.NET枚举

我终于想出了如何做到这一点。我使用了System.EnumToObject方法。它采用我要将其转换为的枚举类型和要使用的整数值。

以下是我的助手库中的代码片段:

local EnumToObject, WinFormsAnchorStylesType = 
                luanet.get_method_bysig(luanet.System.Enum, "ToObject",
                                             "System.Type", "System.Int32"),
                luanet.System.Windows.Forms.AnchorStyles.Top:GetType()
AnchorTop, AnchorLeft, AnchorRight, AnchorBottom = 1, 4, 8, 2
function Anchor(flags)
  return EnumToObject(WinFormsAnchorStylesType, flags)
end

你这样使用它:

Label1 = luanet.System.Windows.Forms.Label()
Label1.Anchor = Anchor(AnchorLeft + AnchorTop + AnchorRight + AnchorBottom)