type AdderType() =
/// Appends to the container.
static member (+)
(cont:DockPanel,child:#UIElement) =
cont.Children.Add child |> ignore
child
Run Code Online (Sandbox Code Playgroud)
当我像上面那样上课并尝试这样的事情.
let dock = DockPanel()
let win = Window(Title = "Check the Window Style", Content = dock)
let menu = dock + Menu()
Run Code Online (Sandbox Code Playgroud)
我得到的错误是None of the types 'DockPanel,Menu' support the operator '+'.
我受到启发,由Phil Trelford的绑定示例制作上述内容,如下所示:
type DependencyPropertyValuePair(dp:DependencyProperty,value:obj) =
member this.Property = dp
member this.Value = value
static member (+)
(target:#UIElement,pair:DependencyPropertyValuePair) =
target.SetValue(pair.Property,pair.Value)
target
Run Code Online (Sandbox Code Playgroud)
以上由于某种原因起作用.我不知道为什么.是否有可能重载+
或其他一些操作符,以便我可以优雅地添加控件到容器?
在类中定义的运算符仅在其中一个参数是类的实例时才起作用,但您可以将运算符定义为全局运算符:
let (++) (cont:DockPanel) (child:#UIElement) =
cont.Children.Add child |> ignore
child
Run Code Online (Sandbox Code Playgroud)
然后应该有以下工作:
let dock = DockPanel()
let win = Window(Title = "Check the Window Style", Content = dock)
let menu = dock ++ Menu()
Run Code Online (Sandbox Code Playgroud)
但说实话,我不认为这种问题是使用自定义运营商的好地方.+
在这里使用是令人困惑的,因为你在任何意义上都没有真正添加两件事.您的运营商不是可交换的,例如(a ++ b) <> (b ++ a)
.
我认为一个更惯用的代码是定义一个命名函数并使用|>
:
let appendTo (cont:DockPanel) (child:#UIElement) =
cont.Children.Add child |> ignore
child
let dock = DockPanel()
let win = Window(Title = "Check the Window Style", Content = dock)
let menu = Menu() |> appendTo dock
Run Code Online (Sandbox Code Playgroud)