【问题标题】:How can I add attributes to a public method in an F# type?如何将属性添加到 F# 类型中的公共方法?
【发布时间】:2011-01-22 00:27:24
【问题描述】:

我只是第一次尝试 F#,并尝试使用它与 C# 项目的互操作。

我在 C# 项目中定义了自定义属性,并在我的新 F# 项目中添加了对该项目的引用。当我尝试为“let”语句定义属性时,“let”是永久私有的,因此属性是否起作用并不重要。当我尝试将“let”语句更改为其他内容时,例如“member”,我被告知属性不能以对象为目标。如果我希望它是公共的并具有属性,我应该如何定义函数?

module FSharp

type public MyClass() = 
    class
        //this one will get the attributes, but is always private and can't be made public
        [<Core.NameAttribute("F# name")>]
        [<Core.DescriptionAttribute("F# desc")>]
        let f1 = "test from F#"

        //this one won't get the attributes, but is public and does return the value
        member this.Function1 = f1
    end

正如我在代码中所述,我似乎遇到了问题。我的属性只设置为目标方法,我可以在“let”语句中设置它们,但不能在“member”语句中设置它们。我确信这很愚蠢,但我提前感谢您的帮助!

【问题讨论】:

    标签: .net f# attributes c#-to-f#


    【解决方案1】:

    问题在于您的member 定义是一个属性,而不是一个方法。正如在 Wesley 的回答中一样,添加一些参数(只需空括号即可)使其成为一种方法。

    (可能另见

    http://blogs.msdn.com/b/timng/archive/2010/04/05/f-object-oriented-programming-quick-guide.aspx

    http://lorgonblog.wordpress.com/2009/02/13/the-basic-syntax-of-f-classes-interfaces-and-members/

    )

    【讨论】:

      【解决方案2】:

      试试这个:

      type myAttribute() =
          inherit System.Attribute()
          ;
      
      type test() = 
          [<myAttribute()>]
          member this.func() = "test from f#"
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-06-20
        • 1970-01-01
        • 2017-05-20
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2011-10-20
        • 2017-02-13
        相关资源
        最近更新 更多