質問

I have an html helper class for my webforms projects. so far it can return strings to create labels and readonly fields.

Public Shared Function DisplayFor(value As String, Optional attributes As String = "") As String
    Return [String].Format("<span class='uneditable-input {0}'>{1}</span>", GetSStyle(attributes), value)
End Function

Now I want to create some overloads that can accept passing the entity property so it can internally check the datatype (from attributes) and display the content formatted, for example. Just as MVC does.

The only problem it's that I don't know how to pass a class property as a function parameter.

役に立ちましたか?

解決

You can pass a property as an Expression(Of Func(Of MyModel, String)) and by that receive an expression in the method that you can analyze and evaluate:

Public Shared Function DisplayFor(Of TModel, TValue)(model As TModel, expr As Expression(Of Func(Of TModel, TValue))) As String
    ' Retrieve the value dynamically
    Dim compExpr = expr.Compile()
    Dim value = compExpr.DynamicInvoke(model)
    Dim retVal As String
    If value Is Nothing Then
        retVal = String.Empty
    Else
        retVal = value.ToString()
    End If
    ' Analyze expression body
    Dim memberAccExpr = DirectCast(expr.Body, 
                          System.Linq.Expressions.MemberAccessExpression)
    Dim attr = memberAccExpr.Member.GetCustomAttributes(typeof(MyDisplayAttribute), false).Cast(Of MyDisplayAttribute)().FirstOrDefault();
    Return retVal
End Function

Call the method like this:

DisplayFor(myModelVar, Function(m) m.MyProperty)

I hope this sample gives you a rough outline on how to handle this. Please note that especially the analysis of the expression body is simplified. In real world code there would be various checks to make sure that the expression matches your expectations.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top