3

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

我想使用 的Anchor属性Control使它们自动调整大小。如果我只设置一个 Anchors(例如 only AnchorStyles.Top),它可以工作,但这并没有真正的意义。我必须设置多个 Anchor,这是通过将它们与“按位或”组合(或仅以数字方式添加它们)来完成的。

在 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中的正确枚举类型?

4

1 回答 1

1

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

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

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)
于 2012-02-24T19:27:35.110 回答