【问题标题】:F# set property in constructor of derived typeF# 在派生类型的构造函数中设置属性
【发布时间】:2016-06-17 17:46:27
【问题描述】:

我有一个继承自 MVC 类 AuthorizeAttribute 的类型。在我的构造函数(它需要一个参数)中,我想设置 Roles 属性,但我收到一个错误“这不是有效的对象构造表达式。显式对象构造函数必须调用备用构造函数或初始化对象的所有字段和指定对超类构造函数的调用。”有人可以帮我解决我做错的事情吗?

尝试 #1:

type MyAuthorizer =
    inherit AuthorizeAttribute

    new([<ParamArray>] roles : string[]) =
        let x = new MyAuthorizer()
        //x.Roles <- ""
        x

尝试 #2。 (同样的错误):

type MyAuthorizer =
    inherit AuthorizeAttribute

    new([<ParamArray>] roles : string[]) =
        {
            inherit AuthorizeAttribute
            Roles = ""
        }

【问题讨论】:

标签: f#


【解决方案1】:

尝试在对基本构造函数的调用中包含属性及其值,如下所示:

type MyAuthorizer([<ParamArray>] roles : string[])    
    inherit AuthorizeAttribute(Roles = "")

【讨论】:

  • 非常优雅。谢谢!
【解决方案2】:

语法有点混乱,但这应该可以。请注意then 关键字,它允许您执行任意副作用,例如分配Roles 的值。

type MyAuthorizer =
    inherit AuthorizeAttribute

    new ([<ParamArray>] roles : string[]) as this = 
        { inherit AuthorizeAttribute() } then
            this.Roles <- ""

【讨论】:

猜你喜欢
  • 2020-02-28
  • 2014-03-16
  • 2014-01-21
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
  • 2015-12-08
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多