C# 是否具有与 VB.NET 的 DirectCast 等效的功能?
我知道它有 () 强制转换和“as”关键字,但这些与 CType 和 TryCast 一致。
明确地说,这些关键字执行以下操作;
CType/() 转换:如果它已经是正确的类型,则转换它,否则寻找类型转换器并调用它。如果未找到类型转换器,则抛出 InvalidCastException。
TryCast/“as”关键字:如果类型正确,则强制转换,否则返回null。
DirectCast:如果类型正确,则进行转换,否则抛出 InvalidCastException。
在我说完上面的内容之后,有些人仍然回答说 () 是等价的,所以我将进一步说明为什么这不是真的。
DirectCast 只允许在继承树上进行缩小或扩大转换。它不像 () 那样支持跨不同分支的转换,即:
C# - 这会编译并运行:
//This code uses a type converter to go across an inheritance tree
double d = 10;
int i = (int)d;
VB.NET - 这不能编译
'Direct cast can only go up or down a branch, never across to a different one.
Dim d As Double = 10
Dim i As Integer = DirectCast(d, Integer)
在 VB.NET 中与我的 C# 代码等效的是 CType:
'This compiles and runs
Dim d As Double = 10
Dim i As Integer = CType(d, Integer)
最佳答案
很明显,您想要的功能不在 C# 中。不过试试这个……
static T DirectCast<T>(object o, Type type) where T : class
{
if (!(type.IsInstanceOfType(o)))
{
throw new ArgumentException();
}
T value = o as T;
if (value == null && o != null)
{
throw new InvalidCastException();
}
return value;
}
或者,即使它与 VB 不同,也可以这样调用它:
static T DirectCast<T>(object o) where T : class
{
T value = o as T;
if (value == null && o != null)
{
throw new InvalidCastException();
}
return value;
}
关于c# - C#'s equivalent to VB.NET' s 直播,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2683847/