2

我正在尝试在 VB.net 中创建一个简单的函数,它需要一些参数来与 TryCast 一起使用。

我的目标是拥有一个可以用来代替 TryCast 的函数,而不是在失败时返回 Nothing,而是应该返回 DbNull。

尽管进行了很多搜索,但我似乎无法获得任何工作。

谢谢。

4

2 回答 2

1

The problem is that you have to have some specific return type for your function. So you can write a function with a signature like this:

Public Function TryCast(Of T)(ByVal item As Object) As T

But you will never be able to make it do what you want, because the type of T is never going to be DBNull (okay, maybe it could happen, but hopefully you get the idea).

Put another way, the type system blocks this. On the one hand, you want to be perfectly explicit about the return type (hence, the cast). On the other hand, you want to be able to return a completely different type. .Net does not allow this, even with dynamic typing. Either a method returns a single fixed type, or it is not declared to return a type at all.

With Option Explicit turned off, you might be able to go for something like this:

Public Function TryCast(Of T)(ByVal item As Object)

However, I don't think this will do what you want, either, because now the returned value is effectively the same as object, and you lose the benefit of any casting.

It works with the normal TryCast() for Nothing, because Nothing can be assigned to any type. DBNull is itself a fixed type, and so is not as flexible.

于 2012-11-13T00:14:06.610 回答
0

简单的答案 - 不可能,这就是原因。假设您有以下代码:

Class A
End Class
Class B : Inherits A
End Class
Class C
End Class

Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
  Dim aaa As A = MyTryCast(Of A)(New B)
  Dim ccc As C = MyTryCast(Of B)(New C)
End Sub

Private Function MyTryCast(Of T As Class)(obj As Object) As Object
  Dim result As Object = TryCast(obj, T)
  If result Is Nothing Then Return Convert.DBNull
  Return result
End Function

MyTryCast完全符合您的要求,因此aaa分配有效。分配DBNullccctype 的变量时会出现问题C。您会期望它分配DBNullC,因为C无法转换为B(常规TryCast将返回Nothing)。相反,您会得到System.InvalidCastException,因为您无法将 a 分配给DBNull自定义类的实例。这里要记住的重要事情 -Nothing可以分配给任何东西,DBNull只能分配给Object. 请参阅此处了解 DBNull 继承层次结构

于 2012-11-13T01:46:14.177 回答