【问题标题】:How can I get a sub-class name in Visual Basic如何在 Visual Basic 中获取子类名称
【发布时间】:2017-09-27 14:42:08
【问题描述】:

我有一个名为 LogException 的 Visual Basic 方法,它在 TRY..CATCH 失败时将信息写入我的异常数据库。该方法具有以下参数:

  1. 方法位置;
  2. 方法名;
  3. 异常;

当我调用该方法时,我会使用以下代码:

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

因此,如果我在名为“Test”的类中的名为“Insert_Test”的方法中调用此代码,我希望第一个参数接收“Test”,第二个参数接收“Insert_Test”,第三个参数接收抛出的异常的确切细节。

只要“测试”类是基类,这一切都可以正常工作。如果“Test”类是子类(例如称为“BigTest”),前两个参数仍将作为“Test”和“Insert_Test”传递。我需要知道的是如何获得确切的类树,以便这种情况下的第一个参数将作为“BigTest.Test”出现。

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

【问题讨论】:

  • 我正在使用嵌套类 - 我尝试将继承用于其他目的,但无法使其工作。

标签: vb.net exception subclass


【解决方案1】:

你可以使用这样的函数:

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

【讨论】:

  • 据我所知,这仍然只返回实际包含被调用方法的类。在我的测试应用程序中,我构建了一个名为“TestClass”的类,并将第二个名为“TestClassEmbedded”的类放入其中。我放入 TestClassEmbedded 的方法称为“TestClassEmbeddedSub”。如果该方法抛出异常,我希望它显示方法名称为“TestClassEmbeddedSub”(我已经可以从 System.Reflection.MethodBase.GetCurrentMethod.Name 获得),方法位置显示为 TestClass.TestClassEmbedded。
  • 你是使用嵌套类还是继承?
  • 我找到了一个关于继承的问题的答案,它实际上回答了你的问题。
【解决方案2】:

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

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

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

【讨论】:

  • 对不起,我应该指定我使用的是 VS2010(甚至不要问)所以我可以参考的最高框架是 4.0。
猜你喜欢
  • 1970-01-01
  • 2020-01-27
  • 2012-03-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-07
  • 1970-01-01
相关资源
最近更新 更多