Joh*_*zen 3 .net reflection nullable
如何使用反射从字符串转换为Nullable?
我有以下代码转换为几乎任何值的几乎任何值类型.在此之上有相当多的代码使用IsAssignableFrom等,所以这是最后的手段.
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());
}
Run Code Online (Sandbox Code Playgroud)
当我想转换为像long这样的可空类型时会出现问题.
显然,漫长的?class没有parse方法.
如何从可空的模板类型中提取解析方法?
编辑:
这是我试图传递的一小段测试:
[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)));
}
Run Code Online (Sandbox Code Playgroud)
而整个功能:
/// <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());
}
}
}
Run Code Online (Sandbox Code Playgroud)
我可能会TypeConverter在这种情况下使用,并且 ; 路上的例子......Nullable.GetUnderlyingType()
static void Main()
{
long? val1 = Parse<long?>("123");
long? val2 = Parse<long?>(null);
}
static T Parse<T>(string value)
{
return (T) TypeDescriptor.GetConverter(typeof(T))
.ConvertFrom(value);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3090 次 |
| 最近记录: |