How to override default(int?) to obtain NULL instead 0
I found here the method:
public static T GetValue<T>(object value)
{
if (value == null || value == DBNull.Value)
return d开发者_Go百科efault(T);
else
return (T)value;
}
How to rewrite it to obtain null if "value" is NULL?
You don't need to rewrite it. You just need to call it as:
GetValue<int?>(value);
How to rewrite it to obtain null if "value" is NULL?
You can’t – int
cannot be null
. You can, however, use Nullable<int>
instead. But this only works for value types. For instance, it won’t work any more for T == string
. In order to accomplish this you will need to write two distinct functions, one for nullable value types and one for reference types.
public T? GetValue<T>(object value) where T : struct
{
if (value == null || value == DBNull.Value)
return null;
else
return (T?)value;
}
Or, terser:
public T? GetValue<T>(object value) where T : struct
{
return (value == null value == DBNull.Value) ? null : (T?)value;
}
(In all cases, T?
is a shortcut for Nullable<T>
.)
int
is a value type not a reference type - it cannot have a value of null
.
Consider using int?
instead if your INT column in the database is nullable.
In C#, an int is a value type and therefore cannot be null as Jakub said. However, you can define a variable :
int? thisValue;
This can be set to null.
Do you mean this:
public T GetValue<T>(object value){
if (value == null)
return null;
else if (value == DBNull.Value)
return default(T);
else
return (T)value;
}
精彩评论