我想和QUOT;(INT)空"返回我0 [英] I want "(int)null" to return me 0
问题描述
我如何能得到0作为整数值从(INT)空
。
How can i get 0 as integer value from (int)null
.
修改1:我想创建一个函数,该函数将返回我在他们各自的数据类型为空RE presentation默认值
EDIT 1: I want to create a function that will return me default values for null representation in their respective datatypes.
编辑2: 我如何可以工作在此的场景使用默认
EDIT 2: How can i work in this scenario for using default.
(INT)值
其中的值可以为空或任意整数值。我不知道值在运行时的数据类型。 但我会保证值要么只包含空值或整数值。
Where Value can be null or any integer value. I dont know datatype of value at run time. But i will assure that Value should either contain null or Integer value only.
推荐答案
您可以使用可空结构
int value = new Nullable<int>().GetValueOrDefault();
您也可以使用默认
关键字
int value = default(int);
随着第二次编辑:
Following 2nd edit:
您需要接收任何类型的参数的函数,所以对象将被使用。你的功能类似于字段&LT; T&GT;
的扩展方法的DataRow
You need a function that receive any type of parameter, so object will be used. Your function is similar to the Field<T>
extension method on a DataRow
public static T GetValue<T>(object value)
{
if (value == null || value == DBNull.Value)
return default(T);
else
return (T)value;
}
使用该功能,如果你想要一个int(和你期望的值是int),你怎么称呼它,如:
Using that function, if you want an int (and you expect value to be an int) you call it like:
int result = GetValue<int>(dataRow["Somefield"]);
这篇关于我想和QUOT;(INT)空&QUOT;返回我0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!