C#的正确铸造和转换(或者,Schrödinger的数据类型)

时间:2011-02-22 03:08:50

标签: c# .net datetime casting

这可能是一个基本的C#问题,但我是从C / C ++背景出发的。

我正在编写一个从Sql Server数据库中获取单个日期值的应用程序。我遇到的问题是,当数据库通过sqlcommand reader读取数据时,我收到一条错误消息:

  

“无法将'System.DateTime'类型的对象强制转换为'System.String'”

奇怪的是,GetString(0)似乎在运行时返回了DateTime。

但是,据我所知,我无法将表达式转换为DateTime。如何从表达式中获取DateTime对象,或将此表达式转换为c#字符串? 这是我的代码:

static public string GetSqlString(string SQLText) 
{
    string result = "";
    SqlDataReader reader;

    SqlConnection connection = new SqlConnection("Data Source=DEVDB\\SQLEXPRESS;" +
                                       "Initial Catalog=TestDB;" +
                                       "Trusted_Connection=Yes;");
    using (connection) {
        SqlCommand sqlcommand = connection.CreateCommand();
        sqlcommand.CommandText = SQLText;
        connection.Open();
        reader = sqlcommand.ExecuteReader();
        if (reader != null)
            if (reader.Read())
            {
                // Code breaks on this Line
                result = reader.GetString(0);
                //////////////////////////////////////////////////////
                // This doesn't seem to work either:
                result = (DateTime)(reader.GetString(0)).ToShortDateString;
                // Visual Studio states that this reader.GetString is a string,
                // oddly enough...
            }
            else
            {
                // Purposely Bogus Value
                result = "01/01/1920";
            }
        connection.Close();
    }
    return result;
}


static public DateTime GetCurrentDateDB()
{
    string dateString;
    dateString = GetSqlString("SELECT [ViewingDate] FROM [TestDB].[dbo].[AppGlobals] as varchar");
    DateTime ComputedDate = DateTime.Parse(dateString); 
    return ComputedDate;
}

我的查询结果,来自SQL Server Managment Studio:

  

ViewingDate
  2010-05-17 00:00:00.000

3 个答案:

答案 0 :(得分:4)

GetString是一种类型安全的方法,可以获得您知道的字符串。

使用GetValue(0)获取可以投射到任何所需内容的对象。

如果您只是在寻找默认的字符串表示,请使用GetValue(0).ToString()

String.Format("{0:d}", reader.GetValue(0));是另一种方法。

((DateTime)reader.GetValue(0)).ToShortDateString();应与其他人建议的解决方案完全相同。 GetDateTime(0)调用为您执行强制转换。这就是你使用GetString得到错误的原因,因为它试图转换为String。

答案 1 :(得分:3)

我猜你想要result = reader.GetDateTime(0).ToShortDateString();

答案 2 :(得分:1)

你应该使用GetDateTime(0).ToString()。

相关问题