c# - 在 C# 中动态更改数据类型

标签 c# asp.net

我想动态转换数据类型。

我的代码:

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/

相关文章:

asp.net - Azure 部署未正确显示 View

c# - 如何在 PC 运行时识别 WOL(Wake On Lan)请求

c# - EF 6 的哪种方法更适合用于从数据库异步获取数据?

c# - MVC 3 级联下拉列表

c# - 使用 edmgen 生成实体类

c# - 如何在 Asp.net 中将 SqlDataReader 字符串格式化为货币格式?

c# - 在服务器端访问客户端变量

.net - 是否有比 ASP.NET 成员(member)提供程序更现代的成员(member)/安全实现

c# - asp.NET LINQ 从数据库中删除

c# - 发生异常时显示窗体 C#