如何实现C#'为'在vb.net值类型的关键字? [英] How to achieve the C# 'as' keyword for value types in vb.net?

查看:205
本文介绍了如何实现C#'为'在vb.net值类型的关键字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大多数我们的发展是在vb.net中完成的(不是我的选择),一个经常使用的code模式采用了对错误转到其次是继续下一步,让所有的数据库字段可以读取一个DirectCast()和任何DBNull的值将被忽略。

目前的code会

 对错误转到ERROR_ code
oObject.Name = DirectCast(oReader.Item(姓名),字符串)
oObject.Value = DirectCast(oReader.Item(值),整数)
ERROR_ code:
继续下一步
 

C#code来代替这一个使去除上的错误code会

  oObject.Name = oReader [名称]作为字符串?的String.Empty;
oObject.Value = oReader [价值]作为INT? ? -1;
 

问题是,这个C#code中的vb.net eqivelent使用TryCast(),它只能用于引用类型(可空类型是值类型),而在C#中的关键字可用于参考,可空类型。

因此​​,在总结没有任何人有vb.net code,做每数据库字段一行同样的事情,在C#code的例子吗?

- 编辑 -

我已经决定我认为是在我们的情况下,最好的解决方案。辅助方法不适合(由于管理),我们不能因为我们只是用.NET 2.0扩展方法(虽然与2008年VS所以我们获得了IF())

  oObject.Name = IF(oReader.IsDBNull(oReader.GetOrdinal(名称))的String.Empty,oReader.GetString(oReader.GetOrdinal(名称)))
oObject.Value = IF(oReader.IsDBNull(oReader.GetOrdinal(值)),0,oReader.GetInt32(oReader.GetOrdinal(值)))
 

解决方案

在VB 9.0,IF相当于一个真正的凝聚操作C#的?。 来源 MSDN

所以,你可以使用:

  oObject.Name = IF(oReader.Item(姓名)。等于(的DBNull.Value)的String.Empty,DirectCast(oReader.Item(姓名),字符串))
 

Most of our development is done in vb.net (not my choice) and one frequently used code pattern uses an 'On Error GoTo' followed by a 'Resume Next' so that all database fields can be read with a DirectCast() and any DBNull values are just ignored.

The current code would be

On Error GoTo error_code
oObject.Name = DirectCast(oReader.Item("Name"), String)
oObject.Value = DirectCast(oReader.Item("Value"), Integer)
error_code:
Resume Next

C# code to replace this an enable the removal of the On Error code would be

oObject.Name = oReader["Name"] as string ?? string.Empty;
oObject.Value = oReader["Value"] as int? ?? -1;

The problem is that the vb.net eqivelent of this C# code uses a TryCast() which can only be used for reference types (nullable types are value types) whilst the C# as keyword can be used for reference and nullable types.

So in summary does anyone have an example of vb.net code that does the same thing as the C# code in a single line per database field?

-EDIT-

I've decided what I think is the best solution in our case. Helper methods would not be suitable (due to management) and we can't have extension methods as we're only using .NET 2.0 (though with VS 2008 so we get the If())

oObject.Name = If(oReader.IsDBNull(oReader.GetOrdinal("Name")), String.Empty, oReader.GetString(oReader.GetOrdinal("Name")))
oObject.Value = If(oReader.IsDBNull(oReader.GetOrdinal("Value")), 0, oReader.GetInt32(oReader.GetOrdinal("Value")))

解决方案

In VB 9.0, "IF" is a true coalescing operation equivalent to C#'s "??". Source MSDN:

So you could use:

oObject.Name = IF(oReader.Item("Name").Equals(DBNull.Value),string.Empty,DirectCast(oReader.Item("Name"), String))

这篇关于如何实现C#'为'在vb.net值类型的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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