在C#中动态更改数据类型 [英] Change data type dynamically in c#
本文介绍了在C#中动态更改数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想动态转换数据类型.
I want to convert the data type dynamically.
我的代码:
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
中获取值.该读取器始终返回字符串值.我将在全球范围内使用此方法.
Here data type only in dynamically. Because I want to assign value this variable in run time. I will get values from SqlDataReader
. This reader return always string values. I am going to use this method globally.
推荐答案
好吧,您所需要的称为类型推断
Well, what you need is called type inference
您不需要事先知道数据类型,就可以让运行时动态地解决它,如下所示:
You don't need to know the data type in advance, you let the runtime solve it on the fly, like this:
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#中动态更改数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文