VB.NET equivalent for C# 7 Type pattern matching

孤街醉人 提交于 2019-12-30 17:14:18

问题


Is there a VB.NET equivalent to this? Note in particular the bmp in the code sample.

public void MyMethod(Object obj)
{
    if (obj is Bitmap bmp)
    {
        // ...
    }
}

Or the short pattern matching syntax with is is exclusive to C#?

EDIT:

I already know these syntaxes:

    If TypeOf obj Is Bitmap Then
        Dim bmp As Bitmap = obj
        ' ...
    End If

or

    Dim bmp As Bitmap = TryCast(obj, Bitmap)
    If bmp IsNot Nothing Then
        ' ...
    End If

What I want to know is whether there is something even shorter, like that new C#7 syntax...

Thank you very much.


回答1:


Currently, no. If you want to implement this, you'll have to use some of the longer formats you already mention in your question.

The C# and VB languages don't always have equivalent features.




回答2:


Use a one line if

If obj is bitmap Then Dim bmp = obj

or use an in-line if (this is the if function)

Dim bmp = If(obj is bitmap, obj, Nothing)

Not quite pattern-matching per se, but is does the same thing.

Couldn't you do it this way in C#:

var bmp = obj is bitmap ? obj : nothing;


来源:https://stackoverflow.com/questions/47495455/vb-net-equivalent-for-c-sharp-7-type-pattern-matching

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!