rene marxis
rene marxis

Reputation: 415

.net and propertyinfo of property

i have some ressourcefile that defines some errorcodes. I'd like to use only strongtyping in my project. I also have to implement some Exception handling that prints the errors defined in the ressourcefile but also the name of the ressourceproperty. Think of it like this: Property-Name is Error1 (Type String) Property-Value is "This is the error"

Now i'd like to have some funktion that prints out: Error1: This is the error

Would it be possible to get the Property-Info of an info, without passing in the property-name as a string? That way i could use the name of the property and the value to output both data.

Something like:

Public Class Form1
        Public Class PropTestClass
            Public Shared ReadOnly Property Prop1 As String
                Get
                    Return "Test1"
                End Get
            End Property

            Public Shared ReadOnly Property Prop2 As String
                Get
                    Return "Test2"
                End Get
            End Property
        End Class


        Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
            TestPrint(PropTestClass.Prop1)
        End Sub

        Public Sub TestPrint(prop As Object)
            Debug.Print(prop) '--> need to output: "Prop1: Test1"
        End Sub
    End Class

Can use reflection, Extentions.

Any hint?

Upvotes: 0

Views: 36

Answers (1)

rene marxis
rene marxis

Reputation: 415

Got this working by using Linq-Expressions

'declare all ressources in Meldungen

'part of class SmartException::Exception
Private m_Message As String
Public Overrides ReadOnly Property Message As String
    Get
        Return m_Message
    End Get
End Property

Public Function SetResMessage(Of TProp)(expression As Expressions.Expression(Of Func(Of Meldungen, TProp)), ParamArray params As Object()) As MySmartException
    Dim body As MemberExpression = TryCast(expression.Body, MemberExpression)
    If body Is Nothing Then
        Throw New ArgumentException("'expression' should be a member expression")
    End If

    RessourceString = GetType(Meldungen).GetProperty(body.Member.Name).GetValue(Nothing, Nothing).ToString
    RessourceID = body.Member.Name
    m_Message = Useful.StringFormat(RessourceID & " : " & RessourceString, params)

    Return Me
End Function

'then use it like this
Throw New SmartException().SetResMessage(Function(f) Meldungen.ID_1084, "testval")

If someone needs it :)

Upvotes: 0

Related Questions