With the following example, two calls are made to ConvertNumericStringObj, it sends back a Type int object both times.
string strValue = "123";
object obj = ConvertNumericStringObj(typeof(int), strValue);
object obj = ConvertNumericStringObj(typeof(int?), strValue);
public static object ConvertNumericStringObj(Type conversion, object value)
{
var t = conversion;
if (t.IsGenericType && t.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
{
if (value == null)
{
return null;
}
t = Nullable.GetUnderlyingType(t);
}
return Convert.ChangeType(value, t);
}
My question is: Is there someway to pass in the string and int?
Type and convert it so it returns a int?
object?
If you want the types to potentially be either int
or int?
, then what you're looking for is "generics". This should get you what you want.
public static T ConvertNumericStringObj<T>(string value)
{
var t = typeof (T);
if (t.IsGenericType && t.GetGenericTypeDefinition() == typeof(Nullable<>))
{
if (string.isNullOrEmpty(value))
return default(T);
t = Nullable.GetUnderlyingType(t);
}
return (T)Convert.ChangeType(value, t);
}
However , I'm curious why you wouldn't just return a nullable integer resulting from int.TryParse()
instead.
public static int? ConvertNumericStringObj(string value)
{
int? x;
if (int.TryParse(value , out x)
return x;
return null;
}
Yes you can. Try Int32.TryParse
.
public static int? ConvertNumericStringObj(string strValue)
{
int x;
if (Int32.TryParse(strValue , out x)
return x;
return null;
}
But I wonder, if you necessarily need to pass int?
?
Edit: as OP asked it to be a little generic, try extension method (roughly) like,
public static T? ConvertNumericStringObj<T>(string strValue)
{
if (string.IsNullOrEmpty(strValue))
return null;
return (T) Convert.ChangeType(strValue, typeof(T));
}
This way, you can then use as:
int? x = strX.ConvertNumericStringObj();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.