根据类型变量将异常强制转换为非能量异常

时间 2019-02-22
阅读 41
点赞 0
收藏 0
连接ama

我想扔一个System.Exception一个给定的Type,这样Type作为Sub哪一个ThrowSException.

然后我会打电话给Sub这样地:Call ThrowEvent("Wrong format: MyString must comply with the following pattern ***, System.FormatException)

到目前为止我想到了这个,但是DirectCast不快乐:

未定义exceptiontype

Public Shared Sub ThrowEvent(ByVal Message As String, ByVal ExceptionType As Type)

    Dim MyException As New System.Exception(Message)
    MyException = DirectCast(MyException, ExceptionType)
    Throw MyException

End Sub

除了界面之外,我从来没有用过DirectCast(通常在玩收藏时)

我找到了this但并没有真正了解整个情况。

我找到了this但是我不明白我应该怎样对待我们(Of T)

建议答案

我明白这是不推荐的,我不会实现这个解决方案,但是为了完整性和帮助理解通用函数是如何工作的,这里有两个解决方案:

.不需要消息

Public Shared Sub ThrowEvent(Of TException As {System.Exception, New})()

    Throw New TException() 'Passing arguments to the creator is not permited

End Sub

.需要消息

Public Shared Sub ThrowEvent(Of TException As {System.Exception})(ByVal MyMessage As String)

    Dim MyException As TException = Activator.CreateInstance(GetType(TException), New Object() {MyMessage})
    Throw MyException

End Sub

同样,这回答了问题,但问题寻求的是一种不被推荐的策略。

👍 0