Convert to Nullable <T> from string using Reflection
How can I convert TO Nullable from String using reflection?
I have the following code to convert TO of almost any type of value given for almost any value. There is a lot of code above to use IsAssignableFrom etc., so this is the last resort.
MethodInfo parse = t.GetMethod("Parse", new Type[] { typeof(string) });
if (parse != null)
{
object parsed = parse.Invoke(null, new object[] { value.ToString() });
return (T)parsed;
}
else
{
throw new InvalidOperationException("The value you specified is not a valid " + typeof(T).ToString());
}
The problem occurs when I want to convert to a null type, such as long ?.
Obviously long? the class does not have an analysis method.
How to extract an analysis method from a template type with a zero value?
EDIT:
Here is a short battery of tests I'm trying to pass:
[Test]
public void ConverterTNullable()
{
Assert.That((int?)1, Is.EqualTo(Converter<int?>.Convert(1)));
Assert.That((int?)2, Is.EqualTo(Converter<int?>.Convert(2.0d)));
Assert.That(3, Is.EqualTo(Converter<long>.Convert(3)));
Assert.That((object)null, Is.EqualTo(Converter<long?>.Convert("")));
Assert.That((object)null, Is.EqualTo(Converter<long?>.Convert(null)));
Assert.That((object)null, Is.EqualTo(Converter<long?>.Convert(DBNull.Value)));
Assert.That((long)1, Is.EqualTo(Converter<long?>.Convert("1")));
Assert.That((long)2, Is.EqualTo(Converter<long?>.Convert(2.0)));
Assert.That((long?)3, Is.EqualTo(Converter<long>.Convert(3)));
}
And the whole function:
/// <summary>
/// Converts any compatible object to an instance of T.
/// </summary>
/// <param name="value">The value to convert.</param>
/// <returns>The converted value.</returns>
public static T Convert(object value)
{
if (value is T)
{
return (T)value;
}
Type t = typeof(T);
if (t == typeof(string))
{
if (value is DBNull || value == null)
{
return (T)(object)null;
}
else
{
return (T)(object)(value.ToString());
}
}
else
{
if (value is DBNull || value == null)
{
return default(T);
}
if (value is string && string.IsNullOrEmpty((string)value))
{
return default(T);
}
try
{
return (T)value;
}
catch (InvalidCastException)
{
}
if (Nullable.GetUnderlyingType(t) != null)
{
t = Nullable.GetUnderlyingType(t);
}
MethodInfo parse = t.GetMethod("Parse", new Type[] { typeof(string) });
if (parse != null)
{
object parsed = parse.Invoke(null, new object[] { value.ToString() });
return (T)parsed;
}
else
{
throw new InvalidOperationException("The value you specified is not a valid " + typeof(T).ToString());
}
}
}
+3
3 answers
. ( , , .)
public static T? ParseToNullable<T>(this string value) where T : struct
{
var parseMethod = typeof(T).GetMethod("Parse", new Type[] { typeof(string) });
if (parseMethod == null)
return new Nullable<T>();
try
{
var value = parseMethod.Invoke(null, new object[] { value.ToString() });
return new Nullable<T>((T)value);
}
catch
{
return new Nullable<T>();
}
}
, , generic type , ( ), :
Nullable.GetUnderlyingType(typeof(T))
, .
+2