Accessing dynamic property in F#

与世无争的帅哥 提交于 2020-01-03 18:45:27

问题


I was trying to access dynamic property in Nancy. In Nancy if pass parameter in query it comes as dynamic property. How can I access that.

There are many discussion / question about this but every where, first it is of creating dynamic and then consuming it. How can I consume what is already created?

Here are two code snippet

public class ParameterModule : NancyModule
    {
        public ParameterModule():base("/{about}")
        {
            this.Get["/"] = (parameters) => "Hello About" + parameters.about;
        }
    }

and for F#

type ParameterModule() as this = 
    inherit NancyModule("/{about}")
    do this.Get.["/"] <- fun parameters -> "Hello" + parameters?("about") :> obj

I can't access about as object don't have that property.

Please let me know if any further information needed.


回答1:


The F# dynamic operator (?) allows you to pass string parameters without using the quotes, achieving a similar syntax to C# dynamic, but you need to define it first for your concrete use case, the compiler just provides the syntax. Try this:

let (?) (parameters:obj) param =
    (parameters :?> Nancy.DynamicDictionary).[param]

type ParameterModule() as this = 
    inherit NancyModule("/{about}")
    do this.Get.["/"] <- fun parameters -> sprintf "Hello %O" parameters?about :> obj



回答2:


I have solved problem by typecasting to dynamicdictionary. If there is any better way please let me know. Will keep the question open till then...

Here is the code that solve the issue

type ParameterModule() as this = 
    inherit NancyModule("/{about}")
    do this.Get.["/"] <- fun parameters -> (parameters :?> Nancy.DynamicDictionary).["about"].ToString() :> obj



回答3:


Maybe this can get you started http://hubfs.net/topic/None/74053



来源:https://stackoverflow.com/questions/17640218/accessing-dynamic-property-in-f

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!