【问题标题】:Is it possible to turn a SqlDbType to a string representation of the default value of the corresponding C# type?是否可以将 SqlDbType 转换为相应 C# 类型的默认值的字符串表示形式?
【发布时间】:2016-12-08 10:56:03
【问题描述】:

假设我有一个 SqlDbType (https://msdn.microsoft.com/en-us/library/system.data.sqldbtype(v=vs.110).aspx) 类型的 C# 变量,例如 BigInt。对应的 .NET FrameWork 类型是 Int64 (https://msdn.microsoft.com/en-us/library/cc716729(v=vs.110).aspx)。所以我想要的值是default(Int64).ToString()

有没有办法动态地做到这一点(即不使用switch 语句的墙)?

【问题讨论】:

  • 如果你有一个变量,你想要的值是不是that_variable.ToString()
  • 获取任何类型的默认值都很容易——您在问题中就是这样做的。所以你的问题并不是你真正要问的。您问是否有一个内置函数可以将 SqlDbType 转换为框架类型。没有。

标签: c# sql asp.net .net tsql


【解决方案1】:

简单的答案是否定的,您必须手动进行转换。有一个完整列表 SQL Server 数据类型映射here

我能想到的最简单的方法是创建几个帮助类来处理转换。 SqlExtension 类包含 ToType 方法,将 SqlDbType 转换为 Type。

public static class SqlExtensions
{
    private static readonly IDictionary<SqlDbType, Type> TypeMap = new Dictionary<SqlDbType, Type>
        {
            { SqlDbType.TinyInt, typeof(byte) },
            { SqlDbType.SmallInt, typeof(short) },
            { SqlDbType.Int, typeof(int)},
            { SqlDbType.BigInt,typeof(long) },
            { SqlDbType.Image, typeof(byte[])},
            { SqlDbType.Bit, typeof(bool)},
            { SqlDbType.DateTime, typeof(DateTime)},
            { SqlDbType.DateTime2, typeof(DateTime)},
            { SqlDbType.DateTimeOffset, typeof(DateTimeOffset)},
            { SqlDbType.NVarChar,typeof(string) },
            { SqlDbType.VarChar, typeof(string)},
            { SqlDbType.Text, typeof(string)},
            { SqlDbType.NText, typeof(string)},
            { SqlDbType.Char, typeof(char)},
            { SqlDbType.NChar, typeof(char)},
            { SqlDbType.Money, typeof(decimal)},
            { SqlDbType.Real, typeof(float)},
            { SqlDbType.Float, typeof(double)},
            { SqlDbType.Time, typeof(TimeSpan)}
            // add the rest here
        };

    public static Type ToType(this SqlDbType type)
    {
        if (TypeMap.ContainsKey(type))
        {
            return TypeMap[type];
        }

        throw new ArgumentException($"{type} is not a supported");
    }
}

TypeExtensions 类有一个扩展方法来获取类型的默认值(作为对象返回)。

public static class TypeExtensions
{
    public static object GetDefault(this Type t)
    {
        Func<object> f = GetDefault<object>; // quick hack to get generic method
        return f.Method.GetGenericMethodDefinition().MakeGenericMethod(t).Invoke(null, null);
    }

    private static T GetDefault<T>()
    {
        return default(T);
    }
}

那么只需像SqlDbType.Bit.ToType().GetDefault().ToString()那样将调用链接在一起即可

class Program
{
    static void Main(string[] args)
    {
        var type = SqlDbType.Bit.ToType();
        Console.Write(SqlDbType.Bit.ToType().GetDefault().ToString());
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2011-12-29
    • 2017-09-12
    • 1970-01-01
    相关资源
    最近更新 更多