c# - C#'s equivalent to VB.NET' s 直播

标签 c# vb.net casting directcast ctype

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/

相关文章:

c# - 连接 2 个变量的 Getter Only 属性上的 DataBinding

c# - 将界面解析为 UIElement(Unity、PRISM、C#)

c# - .NET - RichTextBox 中的长行在 3,510 个字符后换行

vb.net - 如何从标题文本属性获取 DGV 列的设计 > 名称属性

c - 遍历转换为 void* 的数组

c++ - 不寻常的编译器错误转换为无效?

c# - 如何以编程方式从 TFS 获取完整的文件夹历史记录?

.net - 在 VB.NET 中检查空的 TextBox 控件

vb.net - 日期而不是日期时间?

asp.net-mvc-3 - Razor 模型类型转换