简体   繁体   中英

How can I add attributes to a public method in an F# type?

I'm just trying out F# for the first time, and playing around with its interop with C# projects.

I have custom attributes defined in a C# project, and added a reference to that project in my new F# project. When I attempt to define the attributes to a "let" statement, the "let" is permanently private and so it doesn't matter that the attributes work. When I attempt to change the "let" statement to something else, say, "member", I'm told the attributes can't target the object. How should I be defining the function if I want it to be public and have attributes?

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

As I've stated in the code, I seem to have a problem. My attributes are set to only target methods, and I can set them on "let" statements, but not "member" statements. I'm sure this is something silly, but I thank you in advance for your help!

Try this:

type myAttribute() =
    inherit System.Attribute()
    ;

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

The issue is that your member definition is a property, not a method. As in Wesley's answer, add some arguments (just empty parens is fine) to make it a method.

(possibly see also

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

and

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

)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM