C# 相当于 VB.NET 的 DirectCast [英] C#'s equivalent to VB.NET's DirectCast

查看:31
本文介绍了C# 相当于 VB.NET 的 DirectCast的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

C# 是否与 VB.NET 的 DirectCast 等效?

Does C# have an equivalent to VB.NET's DirectCast?

我知道它有 () 类型转换和 'as' 关键字,但它们与 CType 和 TryCast 一致.

I am aware that it has () casts and the 'as' keyword, but those line up to CType and TryCast.

明确地说,这些关键字的作用如下;

To be clear, these keywords do the following;

CType/() 强制转换:如果它已经是正确的类型,则对其进行强制转换,否则查找类型转换器并调用它.如果未找到类型转换器,则抛出 InvalidCastException.

CType/() casts: If it is already the correct type, cast it, otherwise look for a type converter and invoke it. If no type converter is found, throw an InvalidCastException.

TryCast/as"关键字:如果类型正确,则强制转换,否则返回null.

TryCast/"as" keyword: If it is the correct type, cast it, otherwise return null.

DirectCast:如果类型正确,则将其强制转换,否则抛出 InvalidCastException.

DirectCast: If it is the correct type, cast it, otherwise throw an InvalidCastException.

在我把上面说清楚之后,仍然有人回答说 () 是等价的,所以我将进一步解释为什么这不是真的.

After I have spelled out the above, some people have still responded that () is equivalent, so I will expand further upon why this is not true.

DirectCast 只允许在继承树上进行缩小或扩大转换.它不支持像 () 那样跨不同分支的转换,即:

DirectCast only allows for either narrowing or widening conversions on the inheritance tree. It does not support conversions across different branches like () does, i.e.:

C# - 编译并运行:

C# - this compiles and runs:

//This code uses a type converter to go across an inheritance tree
double d = 10;
int i = (int)d;

VB.NET - 这不能编译

VB.NET - this does NOT COMPILE

'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:

The equivalent in VB.NET to my C# code is CType:

'This compiles and runs
Dim d As Double = 10
Dim i As Integer = CType(d, Integer)

推荐答案

您想要的功能显然不在 C# 中.试试这个...

It seems clear that the functionality you want is not in C#. Try this though...

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 不同,也可以这样称呼它:

Or, even though it is different from the VB, call it like:

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# 相当于 VB.NET 的 DirectCast的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆