嗯,你需要的是所谓的类型推断
您不需要提前知道数据类型,您可以让运行时即时解决它,如下所示:
private static void updateValues(SqlDataReader reader)
{
USR_AddressItem item = new USR_AddressItem();
item.UserId = GetConverter(item.UserId)(reader[UserDAL.USR_Address.FieldNames.UserId]);
}
我的魔法就在这里:
static Func<string, T> GetConverter<T>(T example)
{
return (x) => Convert<T>(x);
}
static T Convert<T>(string val)
{
Type destiny = typeof(T);
// See if we can cast
try
{
return (T)(object)val;
}
catch { }
// See if we can parse
try
{
return (T)destiny.InvokeMember("Parse", System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, new object[] { val });
}
catch { }
// See if we can convert
try
{
Type convertType = typeof(Convert);
return (T)convertType.InvokeMember("To" + destiny.Name, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.Public, null, null, new object[] { val });
}
catch { }
// Give up
return default(T);
}