我想动态转换数据类型。
我的代码:
private static void updateValues(SqlDataReader reader)
{
USR_AddressItem item = new USR_AddressItem();
Type ConvertNewType;
ConvertNewType = Type.GetType(item.UserId.GetType().Name);
item.UserId = (ConvertNewType)(reader[UserDAL.USR_Address.FieldNames.UserId]);
}
这里的数据类型只是动态的。因为我想在运行时给这个变量赋值。我将从 SqlDataReader
获取值。此阅读器始终返回字符串值。我将在全局范围内使用此方法。
最佳答案
嗯,你需要的是类型推断
你不需要提前知道数据类型,你让运行时即时解决它,就像这样:
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);
}
关于c# - 在 C# 中动态更改数据类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17676077/