是否有一个VB.NET EX pression是*永远*产生空? [英] Is there a VB.NET expression that *always* yields null?

查看:115
本文介绍了是否有一个VB.NET EX pression是*永远*产生空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们都知道,VB的没有相似,但不等同,到C#的。 (如果你不知道这一点,看看这个答案第一。)

We all know that VB's Nothing is similar, but not equivalent, to C#'s null. (If you are not aware of that, have a look at this answer first.)

只是出于好奇,我想知道以下内容:

Just out of curiosity, I'd like to know the following:

有没有VB.NET EX pression总是产生

Is there a VB.NET expression that always yields null?

要给出一个具体的例子,采取以下语句:

To give a concrete example, take the following statement:

Dim o As Object = If(myBool, 5, ...)

是否有可能取代 ... 的东西,这样 0 5 myBool 的真实,没什么/空 myBool 是假的?

Is it possible to replace ... with something, such that o is 5 when myBool is true and Nothing/null when myBool is false?

显然的解决办法是行不通的:

Obvious solutions that won't work:

  • 没有(见问题链接答案以上),
  • DirectCast(没什么,对象)(抛出一个编译时错误与选项严),
  • DirectCast(没什么,整型?)适用于这个例子,但不工作的一般的(如果你替换 5 5.0 在这个例子中,你需要修改的演员)。
  • Nothing (see the question to the linked answer above),
  • DirectCast(Nothing, Object) (throws a compile-time error with Option Strict On),
  • DirectCast(Nothing, Integer?) works for this example, but does not work in general (if you replace 5 with 5.0 in this example, you'd need to modify the cast).

明显的解决方法(将不会算作答案):

Obvious workarounds (won't count as answers):

  • 在声明一个对象变量或字段,将其设置为没有,并利用它来进行 ...
  • 定义一个方法或属性总是返回没有
  • DirectCast 第二个参数( 5 )以对象
  • Declare an Object variable or field, set it to Nothing and use that for ...,
  • define a method or property that always returns Nothing,
  • DirectCast the second parameter (5) to Object.

注:上面的例子只是一个例子。这个问题本身是写在大胆。

推荐答案

第一个答案我给错过了一些分,但是这应该这样做:

The first answer I gave missed some points, but this should do it:

Dim o As Object = If(myBool, 5, DirectCast(Nullable.GetUnderlyingType(GetType(Integer)), Object))

本使用的事实,<一个href="http://msdn.microsoft.com/en-us/library/system.nullable.getunderlyingtype%28v=vs.110%29.aspx"><$c$c>Nullable.GetUnderlyingType如果你传递一个类型,是不是可空类型将返回一个空引用 - 这整数不是。其他方法存在,如 Type.GetElementType(),或者的GetType(对象).BaseType

This uses the fact that Nullable.GetUnderlyingType will return a null reference if you pass it a type which isn't a nullable value type - which Integer isn't. Other alternatives exist, such as Type.GetElementType(), or perhaps GetType(Object).BaseType.

我检查了,这可与多种不同类型的第二个操作数。

I've checked that this works with multiple different types for the second operand.

这是有点烦,你必须转换为对象 ...我仍然在为替代品......

It's slightly annoying that you have to cast to Object... I'm still working on alternatives for that...

这篇关于是否有一个VB.NET EX pression是*永远*产生空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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