簡體   English   中英

F#如何列出具有自定義屬性的函數?

[英]F# how to list functions with custom attribute?

我正在嘗試創建某種類型的界面,但是我找不到如何在F#中使用自定義屬性,因為MSDN僅顯示CLR屬性的用法。 這是我想要實現的:

open System

type Command (name : string) =
    inherit Attribute()    
    member this.Name = name

[<Command("something")>]
let doSomething () = 
    Console.Write("I'm doing something") 

[<Command("somethingElse")>]
let doSomethingElse () =
    Console.Write("I'm doing something else") 

[<EntryPoint>]
let main args =
    let command = Console.ReadLine()
    // find function where Command.Name = command and call it
    Console.Read()
    0

為了擴展您的答案 ,一種更通用的方法是獲取所有類型,然后過濾具有您要查找的屬性的函數(因為一旦您的應用程序擴展並且不再打包所有內容,您的方法就會崩潰。進入Program類):

let getCommands () =
    let types = Assembly.GetExecutingAssembly().GetTypes()
    let commands = 
        types 
        |> Array.collect (fun typ -> typ.GetMethods())
        |> Array.choose (fun mi -> 
            mi.CustomAttributes 
            |> Seq.tryFind (fun attr -> attr.AttributeType = typeof<Command>)
            |> Option.map (fun attr -> attr, mi))

    let commandsMap = 
        commands
        |> Seq.map (fun (attr, mi) -> 
            let name =
                let arg = attr.ConstructorArguments.[0]
                unbox<string> arg.Value
            name, mi)
        |> Map.ofSeq

    commandsMap

這將從正在執行的程序集中的所有類型中獲取所有功能,然后過濾掉沒有命令屬性的所有內容。 然后,它構建一個映射,其中的鍵是屬性參數,值是函數的MethodInfo

好,找到了。

Reflection.Assembly.GetExecutingAssembly().GetType("Program").GetMethods()

Program類型名在代碼中不可行,因此無法在typeof<Program> ,但是該類型存在並且可以從匯編中獲取。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM