2017-09-27 30 views
3

我有一个名为LogException的Visual Basic方法,它在发生TRY..CATCH故障时将信息写入我的例外数据库。该方法具有以下参数:如何在Visual Basic中获得子类名称

  1. methodLocation;
  2. methodName;
  3. 异常;

当我调用该方法,我会用下面的代码:

_ex.LogException(
    Me.GetType.Name.ToString, 
    MB.GetCurrentMethod.Name.ToString, 
    ex.Message.ToString) 

因此,如果我调用一个类中被称为“Insert_Test”方法的代码名为“测试”,我会期望第一个参数接收“Test”,第二个参数接收“Insert_Test”,第三个接收来自所抛出异常的确切细节。

只要“Test”类是基类,这一切都可以正常工作。如果“Test”类是一个子类(例如称为“BigTest”),则前两个参数仍将作为“Test”和“Insert_Test”传递。我需要知道的是如何获取确切的类树,以便此场景中的第一个参数将作为“BigTest.Test”来完成。

理想情况下,我希望能够做到这一点,而不必将任何值硬编码到我的代码中,以便代码可以“按原样”重新使用。

在此先感谢。

+0

我使用嵌套类 - 我尝试使用继承用于其他目的,并不能使它发挥作用。 –

回答

3

你可以使用这样的功能:

Public Function GetFullType(ByVal type As Type) As String 
    Dim fullType As String = "" 

    While type IsNot GetType(Object) 
     If fullType = "" Then 
      fullType &= type.Name 
     Else 
      fullType = type.Name & "." & fullType 
     End If 

     type = type.BaseType 
    End While 

    Return fullType 
End Function 

,并调用它是这样的:

GetFullType(Me.GetType)

编辑:这好像OP实际使用嵌套类出现,不继承类。在这种情况下,我发现this answer应该能够调整到提供的代码。

代码嵌套类:

Shared Function GetFullType(ByVal type As Type) As String 
    Dim fullType As String = "" 

    While type IsNot Nothing 
     If fullType = "" Then 
      fullType &= type.Name 
     Else 
      fullType = type.Name & "." & fullType 
     End If 

     type = type.DeclaringType 
    End While 

    Return fullType 
End Function 
+0

据我所知,仍然只返回实际包含被调用方法的类。在我的测试应用程序中,我构建了一个名为“TestClass”的类,并在其中放入了另一个名为“TestClassEmbedded”的类。我把它放到TestClassEmbedded中的方法叫做“TestClassEmbeddedSub”。 如果该方法抛出一个异常,我希望它显示方法名称为“TestClassEmbeddedSub”(我已经可以从System获得。Reflection.MethodBase.GetCurrentMethod.Name)和方法位置作为TestClass.TestClassEmbedded。 –

+0

你使用嵌套类还是继承? –

+0

我发现了一个关于继承问题的答案,它实际上回答了你的问题。 –

1

如果可能的话,不要自行创造它。例如,我可以猜测MB.GetCurrentMethod()将读取堆栈跟踪以确定方法名称(这很慢!)。

您应该检查属性CallerMemberNameCallerFilePath & CallerLineNumber满足您的需求。它们由编译器填充,因此不会遇到任何性能问题。

参见: https://blog.codeinside.eu/2013/11/03/caller-information-with-net-4-5-or-who-touched-the-function/

+0

对不起,我应该指定我使用VS2010(甚至不要求),所以我可以参考的最高框架是4.0。 –

相关问题