属性的.net和propertyinfo

时间:2015-02-11 08:29:39

标签: .net reflection

我有一些ressourcefile定义了一些错误代码。 我想在我的项目中只使用强类型。 我还必须实现一些异常处理,它打印ressourcefile中定义的错误,但也打印ressourceproperty的名称。 可以这样想: Property-Name是Error1(类型字符串) 属性值是"这是错误"

现在我想要打印出一些功能: 错误1:这是错误

是否可以获取信息的Property-Info,而不将属性名称作为字符串传递?这样我就可以使用属性的名称和值来输出两个数据。

类似的东西:

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

可以使用反射,延伸。

任何提示?

1 个答案:

答案 0 :(得分:0)

使用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")

如果有人需要它:)