2015-02-11 72 views
0

我有一些ressourcefile定义了一些错误代码。 我只想在我的项目中使用强类型。 我还必须实现一些异常处理,该处理将打印ressourcefile中定义的错误,并且还会显示ressourceproperty的名称。 认为它是这样的: 属性名称是ERROR1(类型字符串) 属性值是“这是错误”.net和属性属性

现在,我想有一些的Funktion打印出: ERROR1:这是错误

是否有可能获得信息的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 

可以使用反射,推广。

任何提示?

回答

0

使用LINQ表达式

'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") 

得到这个工作,如果有人需要它:)